Ich habe eine Eigenschaft _data
im Prototyp als eine Definition für alle erstellten Objekte gespeichert.Javascript Prototyp Vererbung - gemeinsame Eigenschaft
function A() {}
A.prototype._data = [];
Nun werden alle von A
erstellten Objekte haben Eigenschaft _data
.
Ich möchte Prototyp Vererbung, wo _data
Prototyp wird _data
Werte von allen Prototypen in Prototyp-Kette haben.
Weiß nicht direkten Weg, in diesem Beispiel verwende ich einen 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 = [];
Wenn ich Objekt erstellen a
mit Werten aa
und [aa, bb]
b
mit Wert bb
, b.get()
kehrt Objekt. Und später, wenn _data
des Prototyps A
mit aaaa
erweitert wird, gibt die Funktion b.get()
[aa, aaaa, bb]
zurück.
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, um dies zu erreichen? Ich meine mit Konstruktorkorrektur während Object.create
und Referenz Elternprototyp mit constructor.prototype
? Hier
ist eine Demo: http://jsfiddle.net/j9fKP/
Grund für all dies ist Felddefinition für Schema in ORM-Bibliothek, wo Vererbung von Systemen erlaubt. Kinderschema muss alle Felder vom Elternschema haben.
mögliche Duplikate von [Javascript-Objekt-Member, die als Array prototypisiert werden, werden von allen Klasseninstanzen geteilt] (http://stackoverflow.com/questions/4425318/javascript-object-members-that-are-prototyped-as-arrays -become-shared-by-all-cla) – Bergi