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

Ali Salehi picture Ali Salehi · Jan 23, 2012 · Viewed 30.4k times · Source

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?

Answer

nicolaskruchten picture nicolaskruchten · Jan 23, 2012

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.