2013-05-26 55 views
1

我有一些JavaScript代码如下所示扩展JavaScript函数继承阵列

function extends(Child, Parent) { 
    var F = function() { 
    }; 
    F.prototype = Parent.prototype; 
    Child.prototype = new F(); 
    Child.prototype.constructor = Child; 
} 

function Parent() { 
    this.cardArray = []; 
} 

function Child() { 

} 

然后我打电话

extends(Child , Parent); 
var a=new Child(); 

它报告

a.cardArray is undefined 

您的评论欢迎

+0

你有没有在你的代码中定义'cardArray'? –

+0

@SimonM:它在'Parent'中。 –

回答

3

两个问题有:

首先,您不能使用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。