javascript - 扩展javascript函数继承数组

标签 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

欢迎您的评论

最佳答案

这里有两个问题:

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

第二点,也是更重要的一点,就是您没有在任何地方调用 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 = object”,这是正确的。


请注意,真正有效的 JavaScript 继承需要(目前)相当多的管道。你那里有很多,但不是全部。 (例如,调用父方法很尴尬。)我已经完成了 very small library called Lineage FWIW,它会为您完成所有管道工作。

关于javascript - 扩展javascript函数继承数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16757853/

相关文章:

javascript - AngularJS 应用程序在 IE8 中出现奇怪的 'ChildNodes of undefined' 错误

javascript - CORS 问题 : header contains multiple values, 但只允许一个

javascript - Meteor:从服务器方法成功回调后写入数据库

JavaScript 正则表达式 : match all specific chars ignoring nested parentheses

javascript - 如何访问对象属性数组?

javascript - JavaScript 中的运算符 : 5. 0//2.0 = 5?

javascript - 如何使用 Nodejs 永久删除最新版本的 S3 对象

javascript - 使用 Google Apps 脚本,如何将每张演示文稿幻灯片下载为 pdf 格式?

JavaScript - 调用之间函数中的持久数据?

javascript - 使用 Jquery 将 HTML 表单发布数据发送到文件?