Prototype inheritance: can you create an Object.create object?

I am new to prototype inheritance, so I'm trying to figure out the β€œright” way. I thought I could do this:

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"); 

But instead, I get " tbase.BicData.prototype undefined "

In Java they say that I want to have Tdata strong> as the template interface, BicData strong>, to be an implementation of this, and then create objects from it.

Where am I going wrong?

+6
javascript inheritance prototype object-create
source share
1 answer

The problem is that tbase.BicData is an object ( tbase.BicData = Object.create(tData); ), and the prototype property should be used in constructor functions.

Using the Object.create method, I would do something like this:

 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 
+8
source share

All Articles