2014-09-20 28 views
0

我試圖在構造函數中設置原型屬性,但它不起作用,但爲什麼?如果我將該屬性設置爲外部,則一切正常。謝謝!JavaScript繼承(設置原型內部)失敗

var a=function(){ 
    this.x=1; 
} 

var b=function(){ 
    this.prototype=new a(); 

    this.getX=function(){ 
     return this.x; 
    } 
} 

alert(b.prototype); 

var test=new b(); 
alert(test.getX()); 

回答

0

發生什麼事是你正在爲稱爲'原型'的每個「b」實例創建一個公共屬性。不是要繼承的實際原型對象。

var a=function(){ 
    this.x=1; 
} 

var b=function(){ 

this.getX=function(){ 
    return this.x; 
} 
} 

// every new instance of b will inherit 'x: 1' 
b.prototype = new a(); 

console.log(b.prototype); 

var test=new b(); 
console.log(test.getX()); 

檢查出 Prototypal inheritance

+0

確定此鏈接更多的信息,我想我已經瞭解了。所以原型屬性只與構造函數有關,而不是實例。謝謝 – eisverticker 2014-09-21 18:36:02