Skip to content
Advertisement

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

I’m writing a simple serialization / deserialization framework for some application-specific objects.

Consider the following:

JavaScript

At this point, one can ask “What does d1 have that d2 lacks?”

One approach that partially works is to manually assign the methods of d1 to d2:

JavaScript

This has a couple of disadvantages. First, I have to manually assign each method of d1 to d2. Second, d2 gets its own properties, and doesn’t share slots using the prototype mechanism:

JavaScript

So my refined question is: given an object (e.g. d2), is there a way to associate it with the prototype of another object (e.g. d1) so it inherits the same behavior?

Advertisement

Answer

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

JavaScript

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:

JavaScript

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.

JavaScript
Advertisement