ES2015中的箭头函数提供了更简洁的语法。
例子:
构造函数
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: () => {
// ...
}
};
回呼
setTimeout(function() {
// ...
}, 500);
// vs
setTimeout(() => {
// ...
}, 500);
可变函数
function sum() {
let args = [].slice.call(arguments);
// ...
}
// vs
const sum = (...args) => {
// ...
};
tl; dr: 不! 箭头函数和函数声明/表达式不等效,不能盲目替换。
如果要替换的函数 未 使用this
,arguments
并且 未 使用调用new
,则为是。
如此频繁: 这取决于 。箭头函数与函数声明/表达式的行为不同,因此让我们首先看一下它们的区别:
1.词法this
和arguments
箭头函数没有自己的函数this
或没有arguments
约束力。相反,这些标识符像任何其他变量一样在词法范围内解析。这意味着,一个箭头函数内部,this
并且arguments
指的值this
和arguments
在箭头功能环境
定义 中(即,“外”的箭头功能):
// 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
是createObject
自身。
如果需要访问this
当前环境,这将使箭头功能有用:
// currently common pattern
var that = this;
getData(function(data) {
that.data = data;
});
// better alternative with arrow functions
getData(data => {
this.data = data;
});
请注意 ,这也意味着 无法this
通过.bind
或设置箭头功能.call
。
2.不能使用调用箭头功能new
ES2015区分了可 调用的 功能和可 构造的 功能。如果一个函数是可构造的,则可以使用调用它 new
,即new
User()
。如果一个函数是可调用的,则可以不进行调用new
(即正常函数调用)。
通过函数声明/表达式创建的函数是可构造的和可调用的。
箭头函数(和方法)仅可调用。 class
构造函数只能构造。
如果试图调用不可调用函数或构造不可构造函数,则会出现运行时错误。
知道了这一点,我们可以陈述以下内容。
可更换的:
this
或的函数arguments
。.bind(this)
不可 更换:
this
)arguments
(请参阅下文)让我们使用您的示例仔细看一下:
构造函数
这将无法使用,因为无法使用调用箭头功能new
。继续使用函数声明/表达式或使用class
。
原型方法
很有可能没有,因为原型方法通常用于this
访问实例。如果他们不使用this
,则可以替换它。但是,如果您主要关注简洁语法,请使用class
其简洁方法语法:
class User {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
对象方法
与对象文字中的方法类似。如果方法要通过引用对象本身this
,请继续使用函数表达式,或使用新的方法语法:
const obj = {
getName() {
// ...
},
};
Callbacks
这取决于。如果要别名外部this
或正在使用,则绝对应该替换它.bind(this)
:
// old
setTimeout(function() {
// ...
}.bind(this), 500);
// new
setTimeout(() => {
// ...
}, 500);
但是: 如果调用回调的代码显式设置this
为特定值(如事件处理程序,尤其是jQuery),并且回调使用this
(或arguments
),
则不能 使用箭头函数!
可变函数
由于箭头函数没有自己的功能arguments
,因此不能简单地用箭头函数替换它们。但是,ES2015引入了替代方法arguments
:rest参数。
// old
function sum() {
let args = [].slice.call(arguments);
// ...
}
// new
const sum = (...args) => {
// ...
};