什么时候不能使用箭头函数

154 阅读1分钟

箭头函数的缺点?

- 没有arguments
- 无法通过call apply bind改变this

什么时候不能使用箭头函数?

  • 对象的属性
const obj = {
    name:"L",
    getName:() => {
        return this.name //此时this指向window
    }
}
console.log(obj.getName())
  • 原型方法
var obj1 = {
      name: 'L'
}
obj1.__proto__.getName = () => {
  console.log(this.name) //此时this指向window
}
obj1.getName()
  • 构造函数
var Person = (name, age) => {
      this.name = name
      this.age = age
    }
var p = new Person('L', 20)//Uncaught TypeError: Person is not a constructor
  • 动态上下文中的回调函数
<button id="btn1">按钮</button>
<script>
var btn1 = document.getElementById('btn1')
btn1.addEventListener('click', () => {
  console.log(this) //此时this指向window
  this.innerHTML = 'clicked' //不生效了
})
</script>
  • Vue生命周期 和 method
 vue组件本质是对象,this已经指向组件实例了,如果你再用箭头函数this又指向window

注意:React组件本质(非hooks)是Class,是可以用箭头函数的,为什么可以?

class Bar {
  func = () => {
    console.log(this); // 始终指向 Bar
  }
}

这种写法是定义类的实例的属性,相当于下面写法

class Bar {
  constructor(){
    this.func = () => {
      console.log(this); // 始终指向 Bar
    }
  }
}
箭头函数的this的指向和constructor指向一样,因为constructor指向实例,所以func指向实例

具体说明class的箭头函数为什么指向是对的

  • 某些箭头函数代码不易阅读,影响别人阅读浪费时间