Skip to content

Instantly share code, notes, and snippets.

@medikoo
Created April 13, 2012 08:42
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 medikoo/2375144 to your computer and use it in GitHub Desktop.
Save medikoo/2375144 to your computer and use it in GitHub Desktop.
JavaScript fat arrow function
// 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"
@adambabik
Copy link

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.

@medikoo
Copy link
Author

medikoo commented Apr 13, 2012

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"

@adambabik
Copy link

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).

@medikoo
Copy link
Author

medikoo commented Apr 13, 2012

Yeah, it may seem more logical, but I think they wanted to address also other use case, and solve two of them at once:

  1. writing function () { .. } for simple one line functions is too verbose (but it's not that issue for multistatement functions)
  2. 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