Saturday, 27 May 2017

Pass 'this' to a class variable inside constructor

I am interested, how to pass this to a class variable inside a constructor of a parent, so I could use parents methods and access other variables of the parent and call their methods?
Here is my parent class:

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

And here is the example of usage and where is get the following error:

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

        });
    });
  }
}



via user115

No comments:

Post a Comment