2011-09-22 23 views
0

繼承構造函數我有consturctor的繼承問題:無法從父

function Alive(name) { 
    this.name = name; 
} 
var Cat = new Function(); 
Cat.prototype = new Alive(); 
Cat.prototype.constructor = Alive; 
var cat = new Cat('Thomas'); 
alert(cat.name); 

警報顯示不確定的。我做錯了什麼? jsfiddle

回答

3

看起來你想讓父構造函數自動調用,沒有一些額外的工作就不支持。您的代碼應該看起來像下面這樣:

function Alive(name) { 
    this.name = name; 
} 

function Cat(name) { 
    // Call the parent constructor 
    Alive.call(this, name); 
} 

Cat.prototype = new Alive(); 
// This line is to fix the constructor which was 
// erroneously set to Alive in the line above 
Cat.prototype.constructor = Cat; 

var cat = new Cat('Thomas'); 
alert(cat.name); 

如果您使用庫來實現繼承,則不必擔心這一點。如果你不想創建一個空構造函數,它們甚至可以自動調用你的父構造函數。上面的代碼仍然不理想。看看我寫的一篇文章,談論的是「正確的」繼承方式。 http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html

0

因爲貓不接受論據。這是你想要的:

function Alive(name) { 
    this.name = name; 
} 


function Cat(name) { 
    Alive.call(this, name); 
} 

// since there's nothing on the prototype, this isn't necessary. 
// Cat.prototype = new Alive(); 

var cat = new Cat('Tomas'); 

alert(cat.name); 
+0

這個例子沒有設置原型鏈,所以它不是繼承。 –

+0

正如代碼註釋中所提到的,沒有理由將其設置爲無需繼承。如果在原型上定義了任何東西,那就會有所不同。 – Jeremy

+0

設置原型鏈仍然需要,否則'cat instanceof Alive'將返回false –