Re-associating an object with its class after deserialization in Node.js

Object.create() and Object.getOwnPropertyDescriptors() is what you need.

const obj = JSON.parse(JSON.stringify(d1))
const d3 = Object.create(Dog.prototype, Object.getOwnPropertyDescriptors(obj))

The difference between this and OP’s method is that this method sets prototype properties on the prototype, whereas OP’s method sets properties directly on the object. You can see this when you loop through object own properties using for-in loop with hasOwnProperty() method:

for (const i in d1) {
  if (d3.hasOwnProperty(i)) {
    console.log(i)
  }
}

With my method it outputs only _name, but with OP’s method it outputs also getName.

Unfortunately, Object.getOwnPropertyDescriptors() is part of ECMAScript 2017 and it’s supported only in Firefox for now, so you’ll need to use Babel.


Alternatively, you can use Object.setPrototypeOf(). It has better browser support than Object.getOwnPropertyDescriptors(), but it’s discouraged by MDN, because it’s slow.

const d3 = JSON.parse(JSON.stringify(d1))
Object.setPrototypeOf(d3, Dog.prototype)

Leave a Comment