CoffeeScript introduces some fancy new operators and syntax enhancements, but one of the most misunderstood additions is the “fat arrow” (
function keyword was replaced with the “thin arrow” (
->), but the fat arrow serves as the
function keyword and binds the function to the current context.
if callback and @, use arrow the fat
It’s a stupid little phrase, but try to forget it now.
To elaborate just a little, if the function is an event handler or a callback, and you have a reference to the current context (i.e., “@”) in the function, use the the fat arrow. Otherwise, the thin arrow will be fine.
A Little Bit of Context (har!)
The context is the thing to the left of the dot. Here,
bartenderis the context.
If there’s nothing to the left of the dot, the context is the global context.
If the function is an event handler or callback, the context is the event owner or caller. Here, it’s
Rule #3 starts to get a little tricky when callbacks are passed around:
In this example, you’ll get an nasty message when you change the fat arrows to thin arrows in the
Bartender class. Feel free to play with it here: http://jsfiddle.net/uxCCD/7/
Can I Just Use the Fat Arrow All The Time?
Having said that, the fat arrow has been known to quickly fix some failing test. You’ll impress your friends.