我有一些 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
欢迎您的评论
最佳答案
这里有两个问题:
首先,您不能使用extends
作为函数名(除非您使用严格模式并且只在支持严格模式的环境中运行代码)。它是松散模式下的保留字。 (目前未使用,也不太可能,但已保留。)
第二点,也是更重要的一点,就是您没有在任何地方调用 Parent
,因此很自然地,该属性从未被添加到对象中。您需要从 Child
中调用 Parent
以获取它设置的内容,并且您需要这样做以便 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 继承需要(目前)相当多的管道。你那里有很多,但不是全部。 (例如,调用父方法很尴尬。)我已经完成了 very small library called Lineage
FWIW,它会为您完成所有管道工作。
关于javascript - 扩展javascript函数继承数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16757853/