1

How can I avoid doing const self = this in JavaScript/Node.js in each type function?

function Server(config) {
    const self = this;
    this.config = config;

    setTimeout(function() {
        console.log(self.config);
    }, 2000);
}

Server.prototype.foo = function() {
    const self = this;

    setTimeout(function() {
        console.log(self.config);
    }, 4000);
};

module.exports = Server;

It is very error prone (do I use this or self) because you have to look at your scope. Not to mention it feels unnecessary to declare extra variables.

Justin
  • 42,716
  • 77
  • 201
  • 296
  • It's only error prone if you don't use `self` for every subsequent operation – Alnitak May 14 '16 at 21:54
  • `setTimeout` accepts additional args that can be passed on to the callback if you prefer, so `setTimeout(function(self) { console.log(self.config) }, this)` You'll need to fix this in old versions of FF and IE though. –  May 14 '16 at 22:04

2 Answers2

6

You can use Function.prototype.bind to set the this keyword to the provided value:

Server.prototype.listen = function() {
  setTimeout(function() {
    console.log(this.config);
  }.bind(this));
};

Or alternatively in an ES2015 ready environment you use arrow functions which have a lexical this value:

Server.prototype.listen = function() {
  setTimeout(() => {
    console.log(this.config);
  });
};
Jon Koops
  • 8,801
  • 6
  • 29
  • 51
4

Assuming you have ES6 (I see usage of const), arrow functions should be available. More information can be found in this section of the same page.

Joseph
  • 117,725
  • 30
  • 181
  • 234