- 箭头函数没有prototype(原型),所以箭头函数没有本身this;
- 箭头函数的this指向在定义的时候继承自外层第一个普通函数的this。
- 箭头函数的指向不能直接修改。
1. 避免在定义对象方法时使用
例如:
var name = "123";
let obj = {
name:"456",
log:()=>{
console.log(this.name)
}
}
obj.log(); //打印出来的是 123
箭头函数自身没有 this会导致自动继承外层的 this。
2. 避免在定义原型时使用
function Foo(type) {
this.type = type;
}
Foo.prototype.setType = () => {
return this.type; //这里的this指向window
};
const foo = new Foo("data");
console.log(foo.setType()); // undefined