通过'这个'到构造函数

时间:2017-05-27 19:33:09

标签: node.js typescript

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

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) {

        });
    });
  }
}

2 个答案:

答案 0 :(得分:1)

它与构造函数无关。 出现问题的原因是您使用常规函数作为回调和上下文切换(您在那里得到另一个 this )。

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

 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();

您可以看到一个有效的例子here

注意:作为OOP设计决定虽然这不是很干净,但是你引入了循环依赖。尝试注入或至少引入一个接口来分离2个类。

答案 1 :(得分:0)

尝试定义_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);
    }