箭头函数是简化的回调函数,能够在一定程度上简化代码
let num = [1,2,3];
num.map(function(item) {
return item * item;
});
num.map(item => item * item);
以上两种写法结果是一样的,但是并不能说以上两种是完全等价的,其中之一便是两者的this指向问题
箭头函数本身没有this,因此在this取值是都是取其外层代码的this,也就是说箭头函数一经创建,this指向已经被确定了
但是在传统的写法下并不是这样的,传统情况下this是代码执行是的环境,随着代码在不同作用域执行this指向是不同的
例子如下
function Timer() {
this.s1 = 0;
this.s2 = 0;
// 箭头函数
// 执行时this指向Timer
setInterval(() => this.s1++, 1000);
// 普通函数
// 执行时this指向window
setInterval(function () {
this.s2++;
console.log(this.s2);//NaN 因为window下并不存在s2
}, 1000);
}
var timer = new Timer();
setTimeout(() => console.log('s1: ', timer.s1), 3100);
setTimeout(() => console.log('s2: ', timer.s2), 3100);
//3
//0
由以上可以看出箭头函数与普通函数的区别,即在定义箭头函数是其this已经指向其外层代码所在作用域,不会改变
此外当在对象中定义箭头函数是,此时的箭头函数this指向应为对象的外层代码
var x = 11;
var obj = {
x: 22,
say:()=>{
console.log(this.x);
}
}
obj.say()
//11
在定义是say绑定的this为obj所在层的this,对象并不是封闭的作用域,this指向也是在其外层的代码块