一、箭头函数的缺点
  1. 没有arguments;
const fn1 = () => {
  console.log("arguments", arguments);
};
fn1();
  • 1.
  • 2.
  • 3.
  • 4.
  1. 无法通过 apply call bind 改变this,它的this就是声明所在的父作用域的this,跟调用者无关;
const fn2 = () => {
  console.log("this", this);
};
fn2.call({ x: 100 });
  • 1.
  • 2.
  • 3.
  • 4.
  1. 某些箭头函数的代码是难以阅读的
const fn3 = (a, b) => b === undefined ? b => a * b : a * b;
  • 1.
二、不适用箭头函数的场景
  1. 对象方法,this指向问题
const obj = {
  name: "aa",
  getName: () => {
    return this.name;
  },
};
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  1. 原型方法,this指向问题
const obj = {
  name: "aa",
};
obj.__proto__.getName = () => {
  return this.name;
};
console.log(obj.getName());
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  1. 构造函数
const Foo = (name, city) => {
  this.name = name;
  this.city = city;
};
const f = new Foo("aa", "bb");
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  1. 动态上下文中的回调函数,this指向问题
const btn1 = document.getElementById("btn1");
btn1.addEventListener("click", () => {
  // console.log(this === window)
  this.innerHTML = "clicked";
});
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  1. 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());
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.