class中的箭头函数和普通函数区别

1,722 阅读1分钟

直接上代码

class Foo {
  constructor(state) {
      this.state = state
  }
  // 箭头函数
  getName = () => {
      console.log('arrow function: ', this)
      console.log('name: ', this.state.name)
  }
  // 普通函数 
  getAge() {
      console.log('function: ', this)
      console.log('age: ', this.state.age)
  }
}

先实例化一个

    let foo = new Foo({ name: 'foo', age: 16 })

1、通过实例调用方法

调用getName

foo.getName()

//arrow function: ,{"state":{"name":"foo","age":16}
// name: ,foo

调用getAge

foo.getAge()

// function: ,{"state":{"name":"foo","age":16}}
// age: ,16

结论:

    • 如果是普通函数方法,该方法会绑定在构造函数的原型
    • 如果是箭头函数方法,该方法会绑定在构造函数
    • 调用class中的方法,无论是箭头函数方法还是普通函数方法,方法中的this都指向实例对象

2、通过方法的引用调用方法

给getName赋值

let getName = foo.getName
getName()

// arrow function: ,{"state":{"name":"foo","age":16}}
// name: ,foo

给getAge赋值

let getAge = foo.getAge
getAge()

//function: ,undefined
// Uncaught TypeError: Cannot read properties of undefined (reading 'state')

结论:

    • 通过引用来调用箭头函数方法,方法中的this依然指向创建的实例对象。原因:它没有自己的this对象,内部的this就是定义时上层作用域中的this箭头函数this
    • 通过引用调用普通函数方法,方法中的this会始终指向函数的执行环境,这里thisundefined而不是window,。 原因:是因为在class中声明和class表达式中会默认使用严格模式