CoffeeScript Fat Arrows

Lets look at the CoffeeScript usage of the fat arrow aka =>:

1
2
foo = (hello)=>
  console.log(hello)

Which translates to this javascript code:

1
2
3
4
5
var foo;
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
foo = __bind(function(hello) {
  return console.log(hello);
}, this);

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
class MyClass:
    """A simple example class"""
    i = 12345
    def f(self):
        return 'hello world'

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
_.bind = function(func, obj) {
    if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
    var args = slice.call(arguments, 2);
    return function() {
      return func.apply(obj, args.concat(slice.call(arguments)));
    };
  };

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).