ES2015中的箭头函数提供了更简洁的语法。 git
例子: es6
构造函数 github
function User(name) { this.name = name; } // vs const User = name => { this.name = name; };
原型方法 express
User.prototype.getName = function() { return this.name; }; // vs User.prototype.getName = () => this.name;
对象(文字)方法 ide
const obj = { getName: function() { // ... } }; // vs const obj = { getName: () => { // ... } };
回呼 函数
setTimeout(function() { // ... }, 500); // vs setTimeout(() => { // ... }, 500);
可变函数 this
function sum() { let args = [].slice.call(arguments); // ... } // vs const sum = (...args) => { // ... };
tl; dr: 不! 箭头函数和函数声明/表达式不等效,不能盲目替换。
若是您要替换的函数未使用this
, arguments
而且未使用new
arguments
,则为yes。 spa
如此频繁: 这取决于 。 箭头函数的行为与函数声明/表达式的行为不一样,所以让咱们首先看一下它们之间的区别: prototype
1.词汇this
和arguments
rest
箭头函数没有本身的this
或arguments
绑定。 相反,这些标识符像任何其余变量同样在词法范围内解析。 这意味着在arrow函数中, this
和arguments
指的是定义 arrow函数的环境中的this
和arguments
的值(即arrow函数的“外部”):
// 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
。
若是你不是很熟悉this
,能够阅读
2.箭头函数不能用new
调用
ES2015区分了可调用的功能和可构造的功能。 若是一个函数是可构造的,则可使用new
,即new User()
来调用它。 若是一个函数是可调用的,则能够在不使用new
函数的状况下对其进行调用(即正常的函数调用)。
经过函数声明/表达式建立的函数是可构造的和可调用的。
箭头函数(和方法)只能调用。 class
构造函数只能构造。
若是您试图调用不可调用的函数或构造一个不可构造的函数,则会出现运行时错误。
知道了这一点,咱们能够陈述如下内容。
可更换的:
this
或arguments
。 .bind(this)
一块儿使用的函数 不可更换:
this
) arguments
函数(若是它们使用arguments
(请参见下文)) 让咱们使用您的示例仔细看一下:
构造函数
这将没法正常工做,由于没法使用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);
可是:若是调用回调的代码将事件显式地this
值设置为特定值(在事件处理程序中,尤为是在jQuery中),而且回调使用this
(或arguments
), 则不能使用箭头函数!
可变函数
因为箭头函数没有本身的arguments
,所以不能简单地将其替换为箭头函数。 可是,ES2015引入了使用arguments
的替代方法: rest参数 。
// old function sum() { let args = [].slice.call(arguments); // ... } // new const sum = (...args) => { // ... };
相关问题:
更多资源: