Friday, 16 October 2020

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

 user this in JS call back


function MyConstructor(data, transport) {
    this.data = data;
    var boundFunction = (function() { // parenthesis are not necessary
        alert(this.data);             // but might improve readability
    }).bind(this); // <- here we are calling `.bind()` 
    transport.on('data', boundFunction);
}


https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback

No comments:

Post a Comment