1

My application is a simple mysql client used from command line - it connects to database and makes few queries to get information from database. Mysql functionality is encapsulated in a class and problem is since calls to mysql server is async (understandably) - the code flow reaches end of application.

And I am unable to refer to 'this'(Mysql) inside a method of Mysql class.

How do I get around this problem ?

Below is my code.

//CLASS
function Mysql(config) {
  //...
}

//METHOD
Mysql.prototype.getDbInfo = function (cbk) {

  this.showTables(function(e,r) {
    // >>>>>>>>>> PROBLEM HERE using 'this' <<<<<<<<<<<
    console.log(this.configVar);
  });

}

module.exports = Mysql;

//CLASS OBJECT
var test = new Mysql(config);

//METHOD INVOKE
test.getDbInfo(function (err,results) {
  //...
});

1 Answer 1

1

Every time that you jump into a callback function you are loosing the scope of the this object. There are different ways to work around it.

Assign this to another variable

The first solution is to assign the this object to another variable (e.g.: that, self). When you assign one variable to another and the first variable is an object then you keep the reference to the original object and you can use it within the callback. Something like that:

Mysql.prototype.getDbInfo = function (cbk) {
  var self = this;
  self.showTables(function(e,r) {
    // >>>>>>>>>> PROBLEM HERE using 'this' <<<<<<<<<<<
    console.log(self.configVar);
  });

}

Bind the this object to the function

You can bind the this object to the function and like that you set the this keyword set to the provided value (in your case the scope outside of showTables function). You can read the documentation of this and you will be able to understand more:

Mysql.prototype.getDbInfo = function (cbk) {
  this.showTables(function(e,r) {
    // >>>>>>>>>> PROBLEM HERE using 'this' <<<<<<<<<<<
    console.log(self.configVar);
  }.bind(this));

}

Use es6 arrow functions

It is more or less the same solution like the first one. If you use a transpiler you will find out that it is translated like the first solution:

Mysql.prototype.getDbInfo = function (cbk) {
  self.showTables((e,r) => {
    // >>>>>>>>>> PROBLEM HERE using 'this' <<<<<<<<<<<
    console.log(this.configVar);
  });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.