-
-
Save dfparker2002/138173976bfa779af79a81da360c520d to your computer and use it in GitHub Desktop.
JavaScript: Ways to use `this` in callback function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The old way (before ES6) | |
var _self = this; | |
this.element.addEventListener('click', function (event) { | |
_self.doSomething(event); | |
}); | |
// The new way (ES6) | |
this.element.addEventListener('click', (event) => { | |
this.doSomething(event); | |
}); | |
// The recommended way | |
this.element.addEventListener('click', this.doSomething.bind(this)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment