I'm writing a simple serialization / deserialization framework 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)); // serialize / deserialize
> d1
Dog { _name: 'fido' }
> d1.getName()
'fido'
> d2
{ _name: 'fido' }
> d2.getName()
TypeError: d2.getName is not a function
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:
> d2.constructor = d1.constructor
> d2.getName = d1.getName
> d2.getName()
'fido'
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:
> d2
Dog {
_name: 'fido',
constructor: [Function: Dog],
getName: [Function] }
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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…