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

ES6 Class method most efficient way to reference the class instance internally

本文关键字:有效 方法 实例 类方法 在内部 引用 ES6      更新时间:2023-09-26

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

我必须在每个返回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
    });
  }
}

如果您不需要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
    });
  }
}