ESnext中的属性初始化器语法

Ben*_*Ben 7 javascript ecmascript-next

我了解到TC-39建议使用JavaScript classes中的新语法,称为“属性初始化器语法” 。

我还没有找到很多关于它的文档,但是在讨论React时,它被用在了一个蛋头课程中。

class Foo {
  bar = () => {
    return this;
  }
}
Run Code Online (Sandbox Code Playgroud)

这项提议的目的是什么?它与以下内容有何不同:

class Foo {
  bar() {
    return this;
  }
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*ski 6

当使用带有箭头功能的属性初始化器语法时,this该功能将始终引用该类的实例,而对于常规方法,则可以this使用.call()或进行更改.bind()

class Foo {
  constructor() {
    this.test = true;
  }
  bar = () => {
    return this;
  }
}
console.log(new Foo().bar.call({}).test); // true

class Foo2 {
  constructor() {
    this.test = true;
  }
  bar() {
    return this;
  }
}
console.log(new Foo2().bar.call({}).test); // undefined
Run Code Online (Sandbox Code Playgroud)

另外,此语法可用于功能以外的其他用途。