-
-
Save medikoo/2375144 to your computer and use it in GitHub Desktop.
// 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" | |
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:
var Foo = {
getValue: () => "Foo value",
somethingUseful() { return this.getValue() }
}
var Bar = Object.create(Foo, {
getValue: { value: () => "Bar value" } }
});
Bar.somethingUseful() // => "Bar 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 :)
True, true. That's why fat arrow shouldn't be used to declare methods. And that's why I support the idea to introduce skinny arrow.