Lets look at the CoffeeScript usage of the fat arrow aka =>:
1 2 | |
Which translates to this javascript code:
1 2 3 4 5 | |
function.apply
To understand what this does, we need to first understand what is function.apply.
From Mozilla Developer Network:
Calls a function with a given this value and arguments provided as an array.
So, each function can be specified of its this. Sounds weird? perhaps not.
In python, you need to pass self as a first argument to a method. Notice that by method
I classically mean a function that is called on its object.
1 2 3 4 5 | |
In cases like working with Backbone, those functions that are triggered as a reaction to a DOM event, may be be run in the context of the DOM/window, simply because the browser will invoke them in that context.
When that happens this will no longer be the Backbone Model that the mentioned function
belongs to – that’s because there is no notion of ‘belongs to’, there are no classes in
Javascript; but there is a form of those in CoffeeScript.
Fat Arrow
Using a fat arrow gives a function a sense of being a proper method. When we look at the
transformed Javascript code, we see that CoffeeScript generates a __bind function, which
will take your function, and give you back a function that will call function.apply with
a specified this parameters.
In all cases where you would use =>, the current instance of a class will be bound as
this for that function you are defining. That closes up the relation between a function
and an instance; a function that belongs to an instance, would take it as its this argument,
completing its destiny as a proper method.
But I don’t use CoffeeScript!
If you use plain Javascript, you can use underscore.js’s _.bindAll function. Lets see
what it does.
1 2 3 4 5 6 7 | |
After analyzing the CoffeeScript translated version, we identify the function.apply idiom here
pretty easily. However, underscore will call ECMAScript 5’s native bind if available (nativeBind
in the code).
