Last active
July 22, 2021 10:44
-
-
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
This file contains hidden or 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
| 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. |
This file contains hidden or 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
| // 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