Skip to content

Instantly share code, notes, and snippets.

@kevinweber
Created June 24, 2017 01:21
Show Gist options
  • Save kevinweber/479c33f883a3a119f95cb4ffc4161ad1 to your computer and use it in GitHub Desktop.
Save kevinweber/479c33f883a3a119f95cb4ffc4161ad1 to your computer and use it in GitHub Desktop.
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