Created
April 13, 2012 08:42
-
-
Save medikoo/2375144 to your computer and use it in GitHub Desktop.
JavaScript fat arrow function
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
// ES6: | |
var Foo = { | |
getValue: () => "Foo value", | |
somethingUseful: () => this.getValue(); | |
} | |
// same in ES5: | |
var Foo = { | |
getValue: function () { return "Foo value"; } | |
}; | |
Foo.somethingUseful = function () { return this.getValue(); }.bind(Foo); | |
// it may not work as expected with inheritance: | |
var Bar = Object.create(Foo, { | |
getValue: { value: function () { return "Bar value" } } | |
}); | |
Bar.somethingUseful() // => "Foo value" | |
That's right. I saw this shorthand for methods but I just wonder if it's better to introduce this feature (which is more concise than fat/skinny arrow anyway) and have three ways to create functions/methods - fat arrow, shorthand for methods, and old functions. Or introduce skinny arrow which lets developers create methods and dynamic context functions with one, simple syntax. In this way, "old" functions would be redundant (but of course could still work).
Yeah, it may seem more logical, but I think they wanted to address also other use case, and solve two of them at once:
- writing
function () { .. }
for simple one line functions is too verbose (but it's not that issue for multistatement functions) - If we want to relate to context in such simple function in most cases it is lexical parent context (writing extra
.bind(this)
adds to already too verbose statement)
So I see it as remedy for that, additionally we'll get some sugar for descriptors and method declarations, it looks ok for me :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yeah it's good just for simple functions that we put into e.g.
setTimeout
or[].forEach
, or alternatively if we really want to bind context to function.From what I can see here https://gist.github.com/2364818#gistcomment-251610
We have also additional shorthand for methods. Following should work right: