Home » Javascript » How to access the correct `this` inside a callback?

How to access the correct `this` inside a callback?

Posted by: admin June 30, 2018 Leave a comment

Questions:

I have a constructor function which registers an event handler:

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

// Mock transport object
var transport = {
    on: function(event, callback) {
        setTimeout(callback, 1000);
    }
};

// called as
var obj = new MyConstructor('foo', transport);
Answers: