Skip to content

Instantly share code, notes, and snippets.

@dfparker2002
Forked from kevinweber/this.js
Created June 6, 2019 08:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfparker2002/138173976bfa779af79a81da360c520d to your computer and use it in GitHub Desktop.
Save dfparker2002/138173976bfa779af79a81da360c520d 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