一、箭头函数的缺点
- 没有arguments;
const fn1 = () => {
console.log("arguments", arguments);
};
fn1();
- 无法通过 apply call bind 改变this,它的this就是声明所在的父作用域的this,跟调用者无关;
const fn2 = () => {
console.log("this", this);
};
fn2.call({ x: 100 });
- 某些箭头函数的代码是难以阅读的
const fn3 = (a, b) => b === undefined ? b => a * b : a * b;
二、不适用箭头函数的场景
- 对象方法,this指向问题
const obj = {
name: "aa",
getName: () => {
return this.name;
},
};
- 原型方法,this指向问题
const obj = {
name: "aa",
};
obj.__proto__.getName = () => {
return this.name;
};
console.log(obj.getName());
- 构造函数
const Foo = (name, city) => {
this.name = name;
this.city = city;
};
const f = new Foo("aa", "bb");
- 动态上下文中的回调函数,this指向问题
const btn1 = document.getElementById("btn1");
btn1.addEventListener("click", () => {
// console.log(this === window)
this.innerHTML = "clicked";
});
- Vue2生命周期和method,类似于对象的方法(vue的组件是一个对象)
// vue的组件本质上是一个JS对象
{
data(){return{name: 'aa'}},
methods:{
getName: ()=>{
// 报错 Cannot read properties of undefined ( reading 'name')
return this.name
}
},
mounted: ()=>{
// 报错 Cannot read properties of undefined ( reading 'name')
console.log('msg', this.name)
}
}
// React 组件(非hooks)它本质上是一个Es6 class
class Foo {
constructor(name, age) {
this.name = name;
this.age = age;
}
// class中的普通方法可以用箭头函数
getName = () => {
return this.name;
};
}
const f = new Foo("aaa", 25);
console.log(f.getName());