Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoffeeScript, When to use fat arrow (=>) over arrow (->) and vice versa

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?

like image 342
Ali Salehi Avatar asked Oct 10 '22 07:10

Ali Salehi


People also ask

What is the use of fat arrow function?

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 I use arrow function everywhere?

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.

What is advantage of fat arrow function in JavaScript?

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.

Where should you not use arrow functions?

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.


1 Answers

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.

like image 163
nicolaskruchten Avatar answered Oct 11 '22 19:10

nicolaskruchten