引入箭头函数有两个方面的作用:更简短的函数并且不绑定this
普通函数和箭头函数的区别:
箭头函数的this指向规则:
1. 箭头函数没有prototype(原型),所以箭头函数本身没有this
let a = () =>{};
console.log(a.prototype); // undefined
2. 箭头函数的this指向在定义的时候继承自外层第一个普通函数的this。
下面栗子中在一个函数中定义箭头函数,然后在另一个函数中执行箭头函数。
let a,
barObj = { msg: 'bar的this指向' };
fooObj = { msg: 'foo的this指向' };
bar.call(barObj); // 将bar的this指向barObj
foo.call(fooObj); // 将foo的this指向fooObj
function foo() {
a(); // 结果:{ msg: 'bar的this指向' }
}
function bar() {
a = () => {
console.log(this, 'this指向定义的时候外层第一个普通函数'); //
}; // 在bar中定义 this继承于bar函数的this指向
}