Coffeescript: Fat arrow vs thin arrow

In any JavaScript function, the value of this is the object that the function is attached to. However, when you pass functions to other functions or reattach a function to another object, the value of this will change. Sometimes this is what you want, but often you would like to keep the original value of this.

For this purpose, CoffeeScript provides the =>, or fat arrow, which will define a function but at the same time capture the value of this, so that the function can be safely called in any context. This is especially useful when using callbacks, for instance in a jQuery event handler.

class Birthday
  prepare: (action) ->
    @action = action

  celebrate: ->
    @action()

class Person
  constructor: (name) ->
    @name = name
    @birthday = new Birthday
    @birthday.prepare () => "It's #{@name}'s birthday"

m = new Person "Giang"
console.log m.birthday.celebrate()

Notice that the prepare function on the birthday class takes an action function as an argument, to be called when the birthday occurs. Because we’re passing this function using the fat arrow, it will have its scope fixed to the Person object. This means we can still refer to the @name instance variable even though it doesn’t exist on the Birthday object that runs the function.

One thought on “Coffeescript: Fat arrow vs thin arrow

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s