私は次のように子供のコンストラクタで親のメソッドにアクセスしようとしています:Javascriptを/ Node.jsの:ES5子クラスのインスタンスへのアクセス親クラスのメソッド
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)
ヘルプと説明を示します。ありがとうございました!
が 'オブジェクトまたは配列をthis.arg.validity'ていますか? 'ParentClass.apply(this、arguments)'の目的は何ですか? – guest271314
あなたは 'Object.create'を適切に使用していません。ドキュメントによると、**プロトタイプ**があなたが渡すオブジェクトと等しいオブジェクトを作成するので、それにアクセスするには 'ChildClass.prototype .__ proto__'と言うか、' ChildClass.prototype = Object.create(ParentClass.prototype).__ proto__'。また、 'ChildClass.prototype'を新しいオブジェクトとして再定義するのではなく、initメソッドを定義するだけです。 'ChildClass.prototype.init = function(){...}'と言っていますか? – mhodges
@ guest271314 - それは、コンストラクタに渡された引数を持つ親クラスのコンストラクタを呼び出します。 – jfriend00