简体   繁体   中英

What are the key differences between ES6 arrow function and the CoffeeScript fat arrow function?

I am looking to rewrite some CoffeScript code to ECMAScript 2015 (ES6).

Some syntax is very similar such as fat arrow functions:

(param1, param2, paramN) => expression

What are the key differences between ES6 => and CoffeeScript => ?

It would be good to get a heads up from people who already have been in the same situation (converting arrow functions back and forth) and could point out the pitfalls and mistakes to avoid.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM