箭头函数与函数声明/expression式:它们是等价的还是可交换的?

规范性问题如果在使用箭头函数replace函数声明/expression式后发现有关问题的问题,请将其作为该函数的副本closures。

ES2015中的箭头function提供更简洁的语法。 我现在可以用箭头函数replace我所有的函数声明/expression式吗? 我需要注意什么?

例子:

构造函数

function User(name) { this.name = name; } // vs const User = name => { this.name = name; }; 

原型方法

 User.prototype.getName = function() { return this.name; }; // vs User.prototype.getName = () => this.name; 

对象(文字)方法

 const obj = { getName: function() { // ... } }; // vs const obj = { getName: () => { // ... } }; 

callback

 setTimeout(function() { // ... }, 500); // vs setTimeout(() => { // ... }, 500); 

variables函数

 function sum() { let args = [].slice(arguments); // ... } // vs const sum = () => { let args = [].slice(arguments); // ... }; 

tl;博士: 不! 箭头函数和函数声明/expression式是不相同的,不能一味地取代。
如果你想要replace的函数使用this arguments ,并且不用new调用,那么是的。


像往常一样: 这取决于 。 箭头函数具有不同于函数声明/expression式的行为,所以让我们先看看差异:

1.词汇和arguments

箭头函数没有自己的thisarguments绑定。 相反,这些标识符像其他任何variables一样在词法范围中parsing。 这意味着在一个箭头函数内部, this arguments和箭头函数被定义在环境中(即箭头函数的“外部”)引用了thisarguments的值。

 // Example using a function expression function createObject() { console.log('Inside `createObject`:', this.foo); return { foo: 42, bar: function() { console.log('Inside `bar`:', this.foo); }, }; } createObject.call({foo: 21}).bar(); // override `this` inside createObject 

看看这个Plnkr的例子

这个variables是非常不同的timesCalled每次调用该buttontimesCalled增加1。 这回答我的个人问题:

.click( () => { } )

.click(function() { })

在循环中使用时都会创build相同数量的函数,您可以从Plnkr中的Guid计数中看到。

这个例子展示了=>在最后是一个匿名函数:

 Server = (function() { function Server() {} Server.prototype.request = (self) => { console.log("self", self) } Server.prototype.call = function(fun) { var self = this console.log("self", this) return (function() { fun.apply(this, [this]) })(); } return Server; })(); s = new Server() s.call(s.request);