know

性能优化+什么时候不能用箭头函数

高优先级知识点,需要熟练掌握。 前端优化手段 (opens new window)

7000 字前端性能优化总结 (opens new window)

# 1. 什么时候不能用箭头函数

    1. 对象方法中,不适用箭头函数
const obj = {
  name: '张三',
  getName() {
    return this.name
  },
  //错误示例
  getName1: () => {
    return this.name
  }
}
    1. 原型方法中,不适用箭头函数
const obj = {
  name: '张三'
}
obj.__proto__.getName = function () {
  return this.name
}
obj.__proto__.getName1 = () => {
  //错误示例
  return this.name
}
    1. 构造函数也不行!
function Foo(name, sex) {
  this.name = name
  this.sex = sex
}
const Foo1 = (name, sex) => {
  this.name = name
  this.sex = sex
}
console.log('普通的构造函数:', new Foo('张三', '男'))
console.log('箭头函数:', new Foo1('张三', '男'))
    1. 动态上下文中的回调函数
const btn1 = document.getElementById('btn1')
btn1.addEventListener('click', () => {
  //错误
  this.innerHTML = 'clicked'
})
上次更新: