1

我有一些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

欢迎您的评论

4

1 回答 1

3

那里有两个问题:

首先,不能extends用作函数名(除非您使用严格模式并且只在支持严格模式的环境中运行代码)。它是松散模式下的保留字。(目前未使用,也不太可能使用,但已保留。)

第二个也是更重要的是,您没有在任何地方调用 Parent过,因此很自然地,该属性从未添加到对象中。您需要Parent从内部调用Child以获取它设置的内容,并且您需要this在调用Parent. 我们可以通过 来做到这一点Function#call,它允许我们调用一个指定this应该是什么的函数(在我们的例子中,我们希望它与对this的调用相同Child):

function Child (){

    Parent.call(this);
}

因此,总的来说,删除不正确(但无害)的分号,并将extends更改为未保留的内容,并且缩进保持一致,我们得到:

实时复制| 直播源

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 = object”,这是正确的。


请注意,真正有效的 JavaScript 继承需要(目前)相当多的管道。你那里有很多,但不是全部。(例如,对父方法的调用很尴尬。)FWIW,我已经完成了一个非常小的名为的库,它可以为您完成所有工作。Lineage

于 2013-05-26T09:25:43.110 回答