Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JavaScript: Ways to use `this` in callback function
// 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
You can’t perform that action at this time.