2015-10-18 79 views
2

解決JS原型鏈

分配在最底層的原型爲重寫我以前的聲明。感謝Guffa的快速回答。


我一直在瀏覽和種類找到一個很好的答案,MODS,如果這是一個doop對不起。

向代碼.. 我有三種功能,一個,兩個,和三個分別。 我想三個從兩個繼承,兩個從一個繼承。三者的原型應該一路回到一個,它的確如此。 我可以從一個調用方法,而我在三個實例中。但我無法從兩個方法調用方法。

下面是一個例子。

function one() { 
    this.version = 1; 
}; 

one.prototype.one = function() { 
    return 'I live on the one class'; 
}; 

function two() { // extends one 
    this.version = 2; 
}; 

two.prototype.two = function() { 
    return 'I live on the two class'; 
}; 

function three() { // extends two 
    this.version = 3; 
}; 

three.prototype.three = function() { 
    return 'I live on the three class'; 
}; 

two.prototype = Object.create(one.prototype); 
three.prototype = Object.create(two.prototype); 

var x = new three(); 

x.one // -> 'I live on the one class!' 
x.two // -> undefined 
x.three // -> undefined 

當我打電話x.one,我得到的「我住在一個類的預期輸出。 但x.two未定義。 當我看到原型鏈,有沒有方法/兩的鏈上的所有屬性。只有一個原型可以訪問。

我的大腦在哭泣。

編輯 我還沒有嘗試過x.three,但它也是未定義的。也許我繼承的方式是覆蓋原型而不是共享? 雖然如果這是問題,我覺得我可以訪問兩個而不是一個。我不知道爲什麼我可以訪問根類,但是不能訪問根類,甚至不能訪問被調用的實例。就好像三個只是一個參考。

回答

2

您添加方法給他們後更換的twothree原型。原型鏈工作正常,但twothree方法是不是在你的原型後更換它們。

添加方法之前更換原型:

function one() { 
 
    this.version = 1; 
 
}; 
 

 
one.prototype.one = function() { 
 
    return 'I live on the one class'; 
 
}; 
 

 
function two() { // extends one 
 
    this.version = 2; 
 
}; 
 

 
two.prototype = Object.create(one.prototype); 
 

 
two.prototype.two = function() { 
 
    return 'I live on the two class'; 
 
}; 
 

 
function three() { // extends two 
 
    this.version = 3; 
 
}; 
 

 
three.prototype = Object.create(two.prototype); 
 

 
three.prototype.three = function() { 
 
    return 'I live on the three class'; 
 
}; 
 

 
var x = new three(); 
 

 
// Show values in snippet 
 
document.write(x.one() + '<br>'); // -> 'I live on the one class' 
 
document.write(x.two() + '<br>'); // -> 'I live on the two class'

+0

爲了上帝的愛,請不要使用document.write()的例子中。正是這些讓w3school吸收太多的東西。我們主要擺脫它,不要把它帶回來:P –

+0

稀釋是,這是有道理的。我基本上是在他們有機會看到日光之前擦除原型。而且有人可以訪問,因爲我從來沒有重新分配它的原型。完美,非常感謝。 –