Jestem nowy w dziedziczeniu prototypowym, więc staram się zrozumieć "właściwy" sposób. Myślałem, że mogę to zrobić:Dziedziczenie prototypowe: czy można połączyć obiekt Object.create?
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
var tbase = {};
tbase.Tdata = function Tdata() {};
tbase.Tdata.prototype.say = function (data) {
console.log(data);
};
var tData = new tbase.Tdata();
tbase.BicData = Object.create(tData);
tbase.BicData.prototype.say = function (data) {
console.log("overridden: " + data)
};
tbase.BicData.prototype.shout = function (data, temp) {
console.log("SHOUT: " + data + ", " + temp)
};
var test = new tbase.BicData();
tData.say("test1");
test.say("test2");
test.shout("test3", "hope");
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
var tbase = {};
tbase.Tdata = function Tdata() {};
tbase.Tdata.prototype.say = function (data) {
console.log(data);
};
var tData = new tbase.Tdata();
tbase.BicData = Object.create(tData);
tbase.BicData.prototype.say = function (data) {
console.log("overridden: " + data)
};
tbase.BicData.prototype.shout = function (data, temp) {
console.log("SHOUT: " + data + ", " + temp)
};
var test = new tbase.BicData();
tData.say("test1");
test.say("test2");
test.shout("test3", "hope");
Ale zamiast ja dostać „tbase.BicData.prototype jest niezdefiniowany”
W Javie mówić, co chcę to mieć Tdata jako boilerplate ' interface ', BicData za implementację tego, a następnie za utworzenie obiektów z niego.
Gdzie się mylę?
+1 Usunąłem moją odpowiedź, masz rację :) – mck89
To wygląda dobrze! Dziękuję :) – robinhowlett
Myślę, że większość zamieszania OP byłaby unikana, gdyby OP nie mieszał "nowych" i "Object.create". Mówię, wybierz jeden i trzymaj się go. –