When building a class in CoffeeScript, should all the instance method be defined using the =>
("fat arrow") operator and all the static methods being defined using the ->
operator?
Arrow functions allow us to use the fat arrow => operator to quickly define JavaScript functions, with or without parameters. We are able to omit the curly braces and the function and return keywords when creating a new JavaScript function to write shorter function syntax.
Should arrow functions be used e.g.: "everywhere they work", i.e. everywhere a function does not have to be agnostic about the this variable and we are not creating an object. only "everywhere they are needed", i.e. event listeners, timeouts, that need to be bound to a certain scope.
One of the most heralded features in modern JavaScript is the introduction of arrow functions, sometimes called 'fat arrow' functions, utilizing the new token => . These functions two major benefits - a very clean concise syntax and more intuitive scoping and this binding.
An arrow function doesn't have its own this value and the arguments object. Therefore, you should not use it as an event handler, a method of an object literal, a prototype method, or when you have a function that uses the arguments object.
No, that's not the rule I would use.
The major use-case I've found for the fat-arrow in defining methods is when you want to use a method as a callback and that method references instance fields:
class A
constructor: (@msg) ->
thin: -> alert @msg
fat: => alert @msg
x = new A("yo")
x.thin() #alerts "yo"
x.fat() #alerts "yo"
fn = (callback) -> callback()
fn(x.thin) #alerts "undefined"
fn(x.fat) #alerts "yo"
fn(-> x.thin()) #alerts "yo"
As you see, you may run into problems passing a reference to an instance's method as a callback if you don't use the fat-arrow. This is because the fat-arrow binds the instance of the object to this
whereas the thin-arrow doesn't, so thin-arrow methods called as callbacks as above can't access the instance's fields like @msg
or call other instance methods. The last line there is a workaround for cases where the thin-arrow has been used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With