兩個問題有:
首先,您不能使用extends
作爲函數名稱(除非您使用嚴格模式並且僅在支持嚴格模式的環境中運行代碼)。這是鬆散模式中的保留字。 (這不是當前使用並不太可能是,但它保留。)
第二,多sigificant,是你有沒有稱爲Parent
的任意位置,所以很自然,物業從來沒有已被添加到對象。您需要從Child
內撥打電話號碼Parent
以獲取設置的內容,並且您需要這樣做,以便this
在撥打Parent
的電話中正確無誤。我們能做到這一點通過Function#call
,它可以讓我們調用一個函數指定this
應該是什麼(在我們的例子中,我們希望它是一樣this
調用內Child
):
function Child(){
Parent.call(this);
}
所以總,並將不正確的(但無害的)分號刪除,並將extends
更改爲未保留的內容,並且使縮進一致,我們得到:
Live Copy | Live Source
function extend(Child, Parent) {
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
}
function Parent(){
this.cardArray=[];
}
function Child(){
Parent.call(this);
}
extend(Child, Parent);
var a = new Child();
console.log("typeof a.cardArray = " + typeof a.cardArray);
...表示 「的typeof a.cardArray =對象」,這是正確的。
請注意,真正有效的JavaScript繼承需要(現在)一些管道工作。你有很多它,但不是全部。 (例如,對父母方法的調用很尷尬。)我做了一個very small library called Lineage
,它爲你做了所有的管道工作,FWIW。
你有沒有在你的代碼中定義'cardArray'? –
@SimonM:它在'Parent'中。 –