[英]Javascript/Node.js: ES5 child class instance accessing parent class method
我正在嘗試訪問子級構造函數中的父級方法,如下所示:
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()
初始化原型,然后需要向其添加新方法,而不是分配給整個原型,從而替換您剛才放置的所有內容。
這是兩個相互矛盾的陳述:
ChildClass.prototype = Object.create(ParentClass.prototype);
ChildClass.prototype = {...};
解決此問題的一種常用方法是使用Object.assign()
將方法復制到現有原型上:
Object.assign(ChildClass.prototype, {
init: function() {
this.result = this.arg.validity
.filter(function(elem) {
return this.isActive(elem)
}.bind(this));
}
});
這會將您的每個方法復制到已經存在的原型對象中,當您有很多方法時,該方法會更常用。
您也可以一次分配一個新方法(只有幾種方法時更常用):
ChildClass.prototype.init = function() {
this.result = this.arg.validity.filter(function(elem) {
return this.isActive(elem)
}.bind(this));
}
您正在將ChildClass.prototype重新定義為新對象,此對象將在幾行前使用Object.create()
覆蓋您的分配。 相反,只需在其上定義init方法。
嘗試這個:
var ParentClass = function(arg) { this.arg = arg; this.result = {}; }; ParentClass.prototype = { constructor: ParentClass, isActive: function(condition) { return new Date(condition.valid).getTime() <= Date.now(); } }; 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)); }; var instance = new ChildClass({ validity: [{ valid: "01/01/17" }] }); console.log(instance);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.