Skip to content

js面试技能拼图 this

仲灏2022-06-21约 1 分钟

this

箭头函数与普通函数的区别

  • 箭头函数没有argumens
  • 箭头函数的this指向的是父级作用域
  • 箭头函数不能被 call bind apply 修改this指向
  • 某些箭头函数是难以阅读的,比如函数嵌套函数

不适用的情况

  • 对象方法

    js
    const obj = {
      name: 'test',
      getName: () => {
        return this.name // 空的
      }
    }
  • 原型方法

    js
    const obj = {
      name: 'test'
    }
    
    obj.__proto__.getName = () => {
      return this.name // empty
    }
  • 构造函数

    js
    const Foo = (name, age) => {
      this.name = name
      this.age = age
    }
    const f = new Foo('zhangsan', 20) // VM133:5 Uncaught TypeError: Foo is not a constructor
  • 动态上下文中的回调函数

    js
    const btn1 = document.getElementById('btn1')
    btn1.addEventListener('click', () => {
      this.innerHTML = 'clicked' // this = window
    })
  • Vue 生命周期和 method

    • vue 组件本质上就是一个 js 对象
    • react 是可以的, react 组件是一个Class 类