Javascript: How to access the correct this inside a callback

this ("the context") is a special keyword inside each function and its value only depends on how the function was called, not how/when/where it was defined. It is not affected by lexical scopes like other variables (except for arrow functions, see below). Here are some possibilities:


// 1. Using bind method
function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data', ( function () {
        alert(this.data);
    }).bind(this) );
}
var transport = {
    on: function(event, callback) {
        setTimeout(callback, 1000);
    }
};
var obj = new MyConstructor('foo', transport);


// 2. Storing reference to context/this inside another variable
function MyConstructor(data, transport) {
  var self = this;
  this.data = data;
  transport.on('data', function() {
    alert(self.data);
  });
}


// 3.Arrow function
function MyConstructor(data, transport) {
  this.data = data;
  transport.on('data', () => {
    alert(this.data);
  });
}