javascript - Moștenire prototipală: Poți să înlănțuiești Object.create?
Sunt nou în moștenirea prototipală, așa că încerc să înțeleg modalitatea „corectă”. Am crezut că aș putea face asta:
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");
Dar în schimb primesc „tbase.BicData.prototype nu este definit”
În limbajul Java, ceea ce vreau este să am Tdata ca un 'interface' standard, BicData să fie o implementare a acestuia și apoi să instanțiez obiecte din acesta.
Unde greșesc?
Răspuns #1
Problema este că tbase.BicData este un obiect (tbase.BicData=Object.create(tData);), iar proprietatea prototype ar trebui utilizată pe funcțiile constructor.
Profitând de metoda Object.create, aș face ceva de genul acesta:
var tbase = {};
tbase.Tdata = {
say : function (data) {
console.log(data);
}
};
tbase.BicData = Object.create(tbase.Tdata);
tbase.BicData.say = function (data) {
console.log("overridden: " + data)
};
tbase.BicData.shout = function (data, temp) {
console.log("SHOUT: " + data + ", " + temp)
};
var test = Object.create(tbase.BicData);
var tData = Object.create(tbase.Tdata);
tData.say("test1"); // test1
test.say("test2"); // overridden: test2
test.shout("test3", "hope"); // SHOUT: test3, hope
