CoffeeScript Fat Arrow
The CoffeeScript fat arrow binds the current value of “this” into the callback function. Let’s take a look at the example from the CoffeeScript website to see what this means, no pun intended.
Here’s the bit of CoffeeScript.
Account = (customer, cart) -> @customer = customer @cart = cart $('.shopping_cart').bind 'click', (event) => @customer.purchase @cart
Here’s the JavaScript that is compiled from the CoffeeScript.
var Account; Account = function(customer, cart) { this.customer = customer; this.cart = cart; return $('.shopping_cart').bind('click', (function(_this) { return function(event) { return _this.customer.purchase(_this.cart); }; })(this)); };
As you can see, “this”, representing the Account object, gets immediately passed into the callback function as “_this” in the immediately invoked function expression. This allows you to access to the Account object from within the callback.
Let’s say for example we replace the fat arrow with a skinny arrow.
The CoffeeScript
Account = (customer, cart) -> @customer = customer @cart = cart $('.shopping_cart').bind 'click', (event) -> @customer.purchase @cart
compiles into this JavaScript.
var Account; Account = function(customer, cart) { this.customer = customer; this.cart = cart; return $('.shopping_cart').bind('click', function(event) { return this.customer.purchase(this.cart); }); };
As you can see, “this” is no longer passed into the callback, which means the “this” inside the callback will reference the “.shopping_cart” element and not the Account object.
As a rule of thumb, use the fat arrow when you need access to the container object. Use the skinny arrow for everything else.