Javascript-Prototyp-Vererbung - gemeinsame Eigenschaft
Ich habe eine Immobilie gespeichert_data
im Prototyp als Definition für alle erstellten Objekte.
function A() {}
A.prototype._data = [];
Nun werden alle Objekte aus erstelltA
Eigentum haben_data
.
Ich würde gerne Prototypen vererben, wo_data
der Prototyp wird haben_data
Werte aller Prototypen in der Prototypenkette.
Ich kenne keinen direkten Weg, in diesem Beispiel verwende ich einen Getterget()
.
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 = [];
Wenn ich ein Objekt erstellea
mit Wertenaa
und Objektb
mit Wertbb
, b.get()
kehrt zurück[aa, bb]
. Und später, wenn_data
des PrototypsA
wird erweitert mitaaaa
Funktionb.get()
kehrt zurück[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]
Ist es ein guter (Standard-) Weg, dies zu erreichen? Ich meine mit Konstruktorkorrektur währendObject.create
und Referenz Elternprototyp mitconstructor.prototype
?
Hier ist eine Demo:http://jsfiddle.net/j9fKP/
Grund für all dies ist die Felddefinition für das Schema in der ORM-Bibliothek, in der die Vererbung von Schemata zulässig ist. Das untergeordnete Schema muss alle Felder des übergeordneten Schemas enthalten.