我正在尝试在子构造函数中访问父方法,如下所示:
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/