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

时间:2015-12-08 14:47:00

标签: javascript ecmascript-6

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

我是否必须在每个返回承诺的方法中执行'form_elements' => array( 'initializers' => array( 'ObjectManagerInitializer' => 'Application\Initializers\ObjectManagerInitializer', ), ),

var self = this

1 个答案:

答案 0 :(得分: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
    });
  }
}