Created
June 24, 2017 01:21
-
-
Save kevinweber/479c33f883a3a119f95cb4ffc4161ad1 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