JavaScript/Node.js : ES5 child class instance accessing parent class method

标签 javascript node.js

我正在尝试在子构造函数中访问父方法,如下所示:

file1.js

var ParentClass = function(arg) {
    this.arg = arg;
    this.result = {};
};

ParentClass.prototype = {
    constructor: ParentClass,
    isActive: function(condition) {
        return new Date(condition.valid).getTime() <= Date.now())
    }
};

module.exports = ParentClass;

file2.js

var ParentClass = require('file1');

var ChildClass= function(arg) {
    ParentClass.apply(this, arguments);
    this.init();
};

ChildClass.prototype = Object.create(ParentClass.prototype);
ChildClass.prototype.constructor = ChildClass;

ChildClass.prototype = {
    init: function() {
        this.result = this.arg.validity
        .filter(function(elem) {
            return this.isActive(elem)
        }.bind(this));
    }
}

module.exports = ChildClass;

file3.js

var ChildClass= require('file2.js');
var instance = new ChildClass(param);

初始化这样的实例给了我

TypeError: this.isActive is not a function
  at Object.<anonymous> (file2.js)
  at Array.filter (native)
  at Object.ChildClass.init (file2.js)

感谢帮助和解释。谢谢!

最佳答案

您对 ChildClass.prototype 有两个单独的分配。其中一个将凌驾于另一个之上。相反,您需要首先使用 Object.create() 初始化您的原型(prototype),然后您需要向其添加新方法,而不是分配给整个原型(prototype),从而替换您刚刚放在那里的所有内容。

这是两个相互矛盾的陈述:

ChildClass.prototype = Object.create(ParentClass.prototype);

ChildClass.prototype = {...};

解决此问题的一种常见方法是使用 Object.assign() 将方法复制到现有原型(prototype)上:

Object.assign(ChildClass.prototype, {
    init: function() {
        this.result = this.arg.validity
        .filter(function(elem) {
            return this.isActive(elem)
        }.bind(this));
    }
});

这会将您的每个方法复制到已经存在的原型(prototype)对象,当您有很多方法时,此方法更常用。

您也可以一次只分配一个新方法(当您只有几个方法时更常用):

ChildClass.prototype.init = function() {
    this.result = this.arg.validity.filter(function(elem) {
        return this.isActive(elem)
    }.bind(this));
}

关于JavaScript/Node.js : ES5 child class instance accessing parent class method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42125588/

相关文章:

javascript - 如何混合静态和动态本地化文本来本地化每个语言环境具有不同单词定位的 Node.js 应用程序?

javascript - 唯一编号的正则表达式。

javascript - NestJs 将 GRPC 异常转换为 HTTP 异常

javascript - 使用 jQuery 构造带参数的 URL

javascript - Socket.io 无法访问模块

node.js - rethinkdb:如何按两个属性排序并在其中一个属性之间使用

javascript - 将文件上传到 AWS S3 时获取未定义的文件名、文件类型

javascript - jQuery 获取 div 中的所有复选框+文本输入

c# - 在 awesomium 中执行 javascript 来点击一个 div

javascript - 在 NodeJS 中循环后获取新数组值时遇到问题