CodePark/ questions / Serializing class instances
START PRACTICINGPRACTICE
Backend question · Object-oriented programming › Serializing class instances

An Order is cached in Redis as JSON and read back. What does this print?

class Order {
  constructor(items) { this.items = items; }
  get total() { return this.items.reduce((a, b) => a + b, 0); }
}
const json = JSON.stringify(new Order([1, 2]));
const back = JSON.parse(json);
console.log(json, back instanceof Order, typeof back.total);
{"items":[1,2]} false undefined

It prints {"items":[1,2]} false undefined. JSON.stringify copies only an object's own properties that can be listed. The total getter lives on the prototype, so it is skipped. JSON.parse builds plain objects with no prototype link to Order, so methods and getters are gone.

"
{"items":[1,2],"total":3} false number" is tempting, because the getter looks like a property. Rebuild instances after reading, for example with Order.fromJSON(data) or class-transformer.