今天来说一说箭头函数的this指向。
箭头函数( =>)是ES6新特性,它的作用不应该仅仅是缩减代码那么简单,更重要的是它改变了this的指向。
首先来说说箭头函数中用this后,this的指向。依照我个人的理解,箭头函数没有自己的this,它的this会捕获其定义时所在的定义域中的this作为自己的this
例子1:
var obj = {
a : 1,
b : () => {
console.log(this)
},
c : function () {
return () => {
console.log(this)
}
}
}
obj.b() // window
obj.c()() // obj
再举函数的例子,例子2:
function Person () {
this.a = 1
this.b = () => {
console.log(this)
}
this.c = function () {
console.log(this)
}
}
var person = new Person()
person.b() // Person {a: 1, b: ƒ, c: ƒ}
person.c() // Person {a: 1, b: ƒ, c: ƒ}
例子3:
var a = 1
function foo() {
var a = 2
setTimeout(() => {
console.log(this.a)
}, 1000)
}
foo() // 1
因为setTimeout的回调是在全局环境下定义的,所以this指向了全局。
注意事项:
- 因为箭头函数本身没有this,所以用bind/call/apply硬绑定没有任何作用;
- 定义事件回调函数;
- 在创建原型方法上,不能用箭头函数
var name = 'John'
function Person(name) {
this.name = name;
}
Person.prototype.sayName = () => {
return this.name;
};
const person1 = new Person('Mike');
person1.sayName(); // John