Fat-arrow functions in CoffeeScript translate to your usual JavaScript functions, and bind this
to its value in the lexical scope (the scope of definition). Like so:
CoffeeScript
sum = (a, b) =>
return a + b
JavaScript transpilation
var sum;
sum = (function(_this) {
return function(a, b) {
return a + b;
};
})(this);
Arrow functions in ES2015 always do this this
binding.
let arrowFunction = () => this.property
translates to this in ES5
let arrowFunction = (function () { return this.property }).bind(this)
Since this
can't be bound to anything else in arrow functions, they can't be used with the new
keyword, since that needs to bind this
to a new object.
In a "normal" JavaScript function (non-arrow) scope, there's access to a special arguments
variable that is "array like" and is useful to access all the arguments that were passed to the function, regardless of the parameter signature. Of course, this is also true in CoffeeScript fat-arrow functions. In my sum
example, if someone calls it as sum(1, 2, 3)
, one can access the third argument by doing argument[2]
. Arrow functions don't provide arguments
, but have "rest parameters". The latter exists in CoffeeScript too, they call it "splats".
Both CS fat-arrow functions and JS arrow functions support default parameter values. That's not a difference, I know, but worth mentioning IMO.