Skip to content

Instantly share code, notes, and snippets.

@MauricioRobayo
Last active July 22, 2021 10:44
Show Gist options
  • Select an option

  • Save MauricioRobayo/a2481c677a8d1ac97a3c85162591ff83 to your computer and use it in GitHub Desktop.

Select an option

Save MauricioRobayo/a2481c677a8d1ac97a3c85162591ff83 to your computer and use it in GitHub Desktop.
Methods in ES6 objects: using arrow functions https://stackoverflow.com/a/31095976/2002514 #gogofast
Arrow functions are not designed to be used in every situation merely as a shorter version of old-fashioned functions. The most common use case for arrow functions is as short "lambdas" which do not redefine this, often used when passing a function as a callback to some function.
Arrow functions cannot be used to write object methods because, as you have found, since arrow functions close over the this of the lexically enclosing context, the this within the arrow is the one that was current where you defined the object.
// Whatever `this` is here...
var chopper = {
owner: 'Zed',
getOwner: () => {
return this.owner; // ...is what `this` is here.
}
};
// Good
var chopper = {
owner: 'Zed',
getOwner() {
return this.owner;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment