I have saved a property _data
in prototype as a definition for all created objects.
function A() {}
A.prototype._data = [];
Now all objects created from A
have property _data
.
I'd like prototype inheritance, where _data
of prototype will have _data
values from all prototypes in prototype chain.
Don't know direct way, in this example I use a getter get()
.
function A() {}
A.prototype._data = [];
A.prototype.add = function(rec) {
this.__proto__._data.push(rec);
}
A.prototype.get = function() {
if(typeof this.__proto__.constructor.prototype.get == 'function')
{
return this.__proto__.constructor.prototype.get().concat(this.__proto__._data);
}
else
{
return this.__proto__._data || [];
}
}
function B() {}
B.prototype = Object.create(A.prototype, { constructor: { value: B }});
B.prototype._data = [];
When I create object a
with values aa
and object b
with value bb
, b.get()
returns [aa, bb]
. And later if _data
of prototype A
will be extended with aaaa
, function b.get()
returns [aa, aaaa, bb]
.
var a = new A(), b = new B();
a.add('aa');
b.add('bb');
console.log(b.get()); // [aa, bb]
a.add('aaaa');
console.log(b.get()); // [aa, aaaa, bb]
// EDITED - _data in A prototype shoud be without B
console.log(a.get()); // [aa, aaaa]
Is it a good (standard) way how to achieve this? I mean using constructor correction while Object.create
and reference parent prototype with constructor.prototype
?
Here is a demo: http://jsfiddle.net/j9fKP/
Reason for all of this is field definition for scheme in ORM library, where inheritance of schemes is allowed. Child scheme has to have all fields from parent scheme.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…