简体   繁体   English

ES6箭头功能和CoffeeScript胖箭头功能之间的主要区别是什么?

[英]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). 我希望将一些CoffeScript代码重写为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 => ? ES6 =>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). 在CoffeeScript中脂肪箭头的功能转化为你平时的JavaScript函数,并结合this其在词法范围(定义的范围)值。 Like so: 像这样:

CoffeeScript CoffeeScript的

sum = (a, b) =>
  return a + b

JavaScript transpilation JavaScript转换

var sum;
sum = (function(_this) {
  return function(a, b) {
    return a + b;
  };
})(this);

Arrow functions in ES2015 always do this this binding. ES2015中的箭头功能始终执行this绑定。

let arrowFunction = () => this.property

translates to this in ES5 在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. 由于this不能绑定到箭头函数中的任何其他内容,因此它们不能与new关键字一起使用,因为它需要this绑定到新对象。

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. 在“普通”JavaScript函数(非箭头)作用域中,可以访问“数组类似”的特殊arguments变量,并且无论参数签名如何,都可以访问传递给函数的所有参数。 Of course, this is also true in CoffeeScript fat-arrow functions. 当然,在CoffeeScript fat-arrow函数中也是如此。 In my sum example, if someone calls it as sum(1, 2, 3) , one can access the third argument by doing argument[2] . 在我的sum示例中,如果有人将其称为sum(1, 2, 3) ,则可以通过argument[2]访问第三个参数。 Arrow functions don't provide arguments , but have "rest parameters". 箭头函数不提供arguments ,但具有“休息参数”。 The latter exists in CoffeeScript too, they call it "splats". 后者也存在于CoffeeScript中,他们称之为“splats”。

Both CS fat-arrow functions and JS arrow functions support default parameter values. CS胖箭头函数和JS箭头函数都支持默认参数值。 That's not a difference, I know, but worth mentioning IMO. 我知道,这不是一个区别,但值得一提的是IMO。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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