ES6类方法在内部引用类实例的最有效方法

Cat*_*ish 1 javascript ecmascript-6

鉴于下面的类,我如何在返回promise的方法中引用类的实例?

我必须var self = this在每个返回承诺的方法中做吗?

class Group {

  constructor() {}

  foo() {

    // 'this' references the class instance here
    console.log(this.myProp); => 'my value'

    // could do this 'var self = this' but do i need to add this code to every method that returns a promise?

    return Q.promise(function(resolve, reject) {
      // 'this' does NOT reference the class instance here
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

Bri*_*ian 5

如果您不需要promise的上下文,请使用箭头函数

class Group {

  constructor() {}

  foo() {

    // 'this' references the class instance here
    console.log(this.myProp); => 'my value'

    // could do this 'var self = this' but do i need to add this code to every method that returns a promise?

    return Q.promise((resolve, reject) => {
      // 'this' references the class instance here
    });
  }
}
Run Code Online (Sandbox Code Playgroud)