tl;dr: No!箭头函数和函数声明/表达式并不等价,不能盲目替换。
如果您要替换的功能是not use this
, arguments
并且不被调用new
, 好的。
正如经常发生的那样:这取决于。箭头函数与函数声明/表达式有不同的行为,所以让我们先看看差异:
1. 词汇this
and arguments
箭头函数没有自己的函数this
or arguments
捆绑。相反,这些标识符像任何其他变量一样在词法范围内解析。这意味着在箭头函数内部,this
and arguments
参考值this
and arguments
在环境中箭头函数是defined在(即箭头函数“外部”):
// 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
// Example using a arrow function
function createObject() {
console.log('Inside `createObject`:', this.foo);
return {
foo: 42,
bar: () => console.log('Inside `bar`:', this.foo),
};
}
createObject.call({foo: 21}).bar(); // override `this` inside createObject
在函数表达式的情况下,this
指的是在内部创建的对象createObject
。在箭头函数的情况下,this
指的是this
of createObject
itself.
如果您需要访问,这使得箭头函数非常有用this
当前环境:
// currently common pattern
var that = this;
getData(function(data) {
that.data = data;
});
// better alternative with arrow functions
getData(data => {
this.data = data;
});
Note这也意味着not可以设置箭头函数this
with .bind
or .call
.
如果你不是很熟悉this
,考虑阅读
- MDN-这个 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
2. 不能用以下方式调用箭头函数new
ES2015 区分的函数是call能够和功能是构造有能力的。如果函数是可构造的,则可以使用以下命令调用它new
, i.e. new User()
。如果一个函数是可调用的,则无需调用它new
(即正常的函数调用)。
通过函数声明/表达式创建的函数既可构造又可调用。
箭头函数(和方法)只能调用。class
构造函数只能构造。
如果您尝试调用不可调用的函数或构造不可构造的函数,您将收到运行时错误。
知道了这一点,我们可以做出以下陈述。
可更换:
- 不使用的功能
this
or arguments
.
- 与使用的函数
.bind(this)
Not可更换:
- 构造函数
- 添加到原型的函数/方法(因为它们通常使用
this
)
- 可变参数函数(如果它们使用
arguments
(见下文))
- 生成器函数,需要
function*
符号
让我们使用您的示例仔细看看这一点:
构造函数
这是行不通的,因为箭头函数不能用new
。继续使用函数声明/表达式或使用class
.
原型方法
很可能不会,因为原型方法通常使用this
来访问实例。如果他们不使用this
,然后就可以更换它了。但是,如果您主要关心简洁的语法,请使用class
以其简洁的方法语法:
class User {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
对象方法
对于对象字面量中的方法也是如此。如果该方法想要通过以下方式引用对象本身this
,继续使用函数表达式,或者使用新的方法语法:
const obj = {
getName() {
// ...
},
};
回调
这取决于。如果你给外部别名,你绝对应该替换它this
或正在使用.bind(this)
:
// old
setTimeout(function() {
// ...
}.bind(this), 500);
// new
setTimeout(() => {
// ...
}, 500);
But:如果调用回调的代码显式设置this
到一个特定的值,事件处理程序经常出现这种情况,尤其是 jQuery,并且回调使用this
(or arguments
), you cannot使用箭头函数!
可变参数函数
由于箭头函数没有自己的arguments
,你不能简单地用箭头函数替换它们。然而,ES2015 引入了一种替代方法arguments
: the 剩余参数 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters.
// old
function sum() {
let args = [].slice.call(arguments);
// ...
}
// new
const sum = (...args) => {
// ...
};
相关问题:
- 我什么时候应该在 ECMAScript 6 中使用箭头函数? https://stackoverflow.com/q/22939130/218196
- ES6 箭头函数是否有自己的参数? https://stackoverflow.com/q/33288998/1048572
- ES6 箭头函数和使用 Function.prototype.bind 绑定的函数之间有什么区别(如果有)? https://stackoverflow.com/q/32535110/1048572
- 如何使用箭头函数(公共类字段)作为类方法? https://stackoverflow.com/q/31362292/1048572
更多资源:
- MDN - 箭头函数 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions