将“this”传递给构造函数中的类variables

我感兴趣,如何将其传递给父类的构造函数中的类variables,所以我可以使用父类方法并访问父类的其他variables并调用它们的方法?
这是我的父类:

 var async = require('async'); var Rater = require('./rater') var Similars = require('./similars') var Suggestions = require('./suggestions'); module.exports = class Engine { constructor() { this.likes = new Rater(this,'likes'); this.dislikes = new Rater(this,'dislikes'); this.similars = new Similars(this); this.suggestions = new Suggestions(this); } 

这里是使用的例子,并在哪里得到以下错误:

 Cannot read property 'engine' of undefined at --\\classes\rater.js:89:19 

 module.exports = class Rater { constructor(engine,kind) { this.type = kind; this.engine = engine; if(kind == 'likes') //database schemes this.db = Likes_db; else if(kind == 'dislikes') this.db = Dislikes_db; else if(kind == 'similars') this.db = Similars_db; else if(kind == 'suggestions') this.db = Suggestions_db; } //.. //other methods //.. remove(user,item,done) { this.db.remove({user: user,item: item},(err) => { if(err) return done(err); async.series([ function(done) { this.engine.similars.update(user,done); //error-cant enter the method }, function(done) { this.engine.suggestions.update(user,done); } ],function(done) { }); }); } } 

它与构造函数无关。 出现这个问题的原因是你正在使用一个常规的函数作为callback,上下文切换(你会得到另一个)。

使用箭头function来保持相同的上下文。

  async.series([ (done) => { this.engine.similars.update(user,done); //error-cant enter the method }, (done) => { this.engine.suggestions.update(user,done); } ],function(done) { }); 

简单地做这个工作正常:

 class Rather { constructor(engine: Engine) { engine.method(); } } class Engine { constructor() { new Rather(this); } method() { console.log('ENgine'); } } new Engine(); 

你可以在这里看到一个工作的例子。

注意 :作为一个OOPdevise决定,虽然这不是很干净,但是您正在引入循环依赖。 尝试进行注射或至less引入一个界面来分隔2个类。

尝试定义一个_this var,然后将其赋予参数:

 module.exports = class Engine { var _this = this, _constructor = (<any>this).constructor; constructor() { this.likes = new Rater(_this,'likes'); this.dislikes = new Rater(_this,'dislikes'); this.similars = new Similars(_this); this.suggestions = new Suggestions(_this); }