vwhaleapps
9/18/2019 - 9:15 AM

CoffeeScript. What difference between => and ->

CoffeeScript. What difference between => and ->

# The fat arrow => defines a function bound to the current value of this.
# This is handy especially for callbacks.
# Notice the generated differences

# CoffeeScript:

foo = () -> this.x + this.x;
bar = () => this.x + this.x;

# JavaScript

# var bar, foo,
#   _this = this;
# foo = function() {
#   return this.x + this.x;
# };
# bar = function() {
#   return _this.x + _this.x;
# };

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