两个问题有:
首先,您不能使用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'中。 –