2010-02-19 49 views
6

我是新來的原型繼承,所以我試圖理解'正確'的方式。我想我能做到這一點:原型繼承:您可以鏈接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"); 

而是我得到「tbase.BicData.prototype是不確定的

在Java中說,我要的是有TDATA作爲一個樣板「接口',BicData是一個實現,然後從它實例化對象。

我哪裏錯了?

回答

8

問題是tbase.BicData是一個對象(tbase.BicData = Object.create(tData);),並且應該在構造函數上使用prototype屬性。

服用Object.create方法的優點,我會做這樣的事情:

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 
+3

+1我已經刪除了我的答案,你是對的:) – mck89 2010-02-19 17:28:43

+0

這看起來很不錯!謝謝:) – robinhowlett 2010-02-19 18:34:06

+1

我認爲如果OP沒有混合使用'new'和'Object.create',大多數OP的混淆都會被避免。我說挑一個並堅持下去。 – 2012-02-02 09:05:00