ES6标准新增了一种函数定义方式:箭头函数(arrow function)。它拥有更简洁的语法,并且不存在普通函数对象所拥有的 this, arguments, super, 和 new.target. 箭头函数通常用于替代匿名函数,并且不能够作为构造器使用。
例子
下面是一些箭头函数使用的例子:
x => x * x
上面的箭头函数等价于:
function (x){
return x*x;
}
如果箭头函数右侧表达式存在多于一条语句,那么需要使用{}
显示的括起来:
x => {
if (x > 0) {
return x * x;
}
else {
return - x * x;
}
}
箭头函数特性
箭头函数看上去只是匿名函数的一种简写形式,然而箭头函数与匿名函数最明显的区别在于:箭头函数不会绑定this的值。
下面是一个最常见的使用箭头函数的例子:
function Person(){
this.age = 0;
setInterval(() => {
this.age++; // |this| properly refers to the Person object
}, 1000);
}
var p = new Person();
如果不使用箭头函数:
function Person() {
// The Person() constructor defines `this` as an instance of itself.
this.age = 0;
setInterval(function growUp() {
// In non-strict mode, the growUp() function defines `this`
// as the global object (because it's where growUp() is executed.),
// which is different from the `this`
// defined by the Person() constructor.
this.age++;
}, 1000);
}
var p = new Person();
不使用箭头函数的场景下,我们会得到undefined
的错误。因为setInterval
中执行的函数growUp(),本质上是在全局环境下执行的,因此growUp()函数中的this.age++
中的this指向的全局环境中的window对象。而使用箭头函数,则可以完美解决这个问题,因为箭头函数的执行上下文对象并不会保存this,而是像查找普通变量一样沿着作用域链查找this的值。
如果不使用箭头函数,可以使用暂存this
的方式来解决:
function Person() {
var that = this;
that.age = 0;
setInterval(function growUp() {
// The callback refers to the `that` variable of which
// the value is the expected object.
that.age++;
}, 1000);
}
不仅仅是this
,箭头函数实际上也不会绑定arguments, super, 和 new.target.
网友评论