Affect this in a variable instead of using the fat arrow in coffeescript

83 views Asked by At

What is the difference between using the fat arrow (bind the function to the current value of this), and putting the value of @ in a variable?

Fat arrow

Account = (customer, cart) ->
  @customer = customer
  @cart = cart

  $('.shopping_cart').bind 'click', (event) =>
    @customer.purchase @cart

and

Account = (customer, cart) ->
  @customer = customer
  @cart = cart

  self = @
  $('.shopping_cart').bind 'click', (event) ->
    self.customer.purchase self.cart

@ suggests that using the fat arrow avoid cluttering up the surrounding scope. How?

1

There are 1 answers

1
Joe Lee-Moyet On BEST ANSWER

I benchmarked your two snippets along with two other fat-arrow solutions that I feel are more idiomatic as they use CoffeeScript's class syntax:

class AccountWithFatCallback
  constructor: (@customer, @cart) ->
    $('.shopping_cart').bind 'click', (event) =>
      @customer.purchase @cart

class AccountWithFatProtoMethod
  constructor: (@customer, @cart) ->
    $('.shopping_cart').bind 'click', @onClickCart
  onClickCart: => 
    @customer.purchase @cart

All of these were compiled using the latest CoffeeScript compiler, v1.8.0, and you can see the benchmark on jsPerf. The performance difference between the four implementations was minimal (~5% or so), so I'd suggest that the determining factor of what to use should be readability and consistency of your codebase, but I'd strongly suggest you try using CoffeeScript classes as they've a lot to offer to that end.

The only performance caveat I'd raise is to avoid creating fat-arrow anonymous functions many times if you have the option of creating them once and re-using the same bound function. Using fat-arrow prototype methods achieves this by implicitly binding the method once in the constructor.