I am writing a simple serialization / deserialization structure for some application specific objects.
Consider the following:
"use strict";
function Dog(name) { this._name = name; };
Dog.prototype.constructor = Dog;
Dog.prototype.getName = function() { return this._name; }
var d1 = new Dog('fido');
var d2 = JSON.parse(JSON.stringify(d1));
> d1
Dog { _name: 'fido' }
> d1.getName()
'fido'
> d2
{ _name: 'fido' }
> d2.getName()
TypeError: d2.getName is not a function
At this stage, you can ask the question: "What d1is missing d2?"
One approach that partially works is to manually assign the d1 methods to d2:
> d2.constructor = d1.constructor
> d2.getName = d1.getName
> d2.getName()
'fido'
This has several disadvantages. First, I need to manually assign each method d1 to d2. Secondly, d2 gets its own properties and does not use slots using the prototype mechanism:
> d2
Dog {
_name: 'fido',
constructor: [Function: Dog],
getName: [Function] }
So, my clarified question: an object is asked (for example d2), is there a way to associate it with a prototype of another object (for example d1) so that it inherits the same behavior?