我試圖創建一個新類Dog
是通過原型繼承繼承了Animal
類:爲什麼我不能在JavaScript代碼中繼承Animal類的原型?
function Animal() {
this.name = "animal";
this.writeName = function() {
document.write(this.name);
}
}
function Dog() {
this.name = "dog";
this.prototype = new Animal();
}
new Dog().writeName()
不過,我得到一個JavaScript錯誤:Uncaught TypeError: Object #<Dog> has no method 'say'
。
爲什麼? Dog
對象不應該保留Animal
對象作爲原型嗎?
你肯定你粘貼正確的代碼?單詞'say'不會在那裏出現一次。 –
因爲沒有課? ;)但問題是'this'已經是*錯誤的對象*(以及[[原型]]爲時太晚而不能用於'new')。 – 2012-06-30 01:32:14
順便說一句,使用console.log而不是document.write和alert。從長遠來看,這會讓你的生活變得更加輕鬆。 – hugomg