在承诺中访问 ES6 中的这个对象

Accessing this object in ES6 inside a promise

我有一个 ES6 class,它有一个延迟对象作为实例变量。我正在尝试访问 angularjs promise 中的 this 对象,类似于以下内容,但是根据 babel 的说法,this 是未定义的:

class MyClass {

  constructor($q) {
    this.deferred_ = $q.defer();
  }

  myMethod() {
    this.deferred_.promise.then(data => {
      console.log(this);
    });
  }
}

不知何故我想我应该使用两个箭头函数将 this 绑定到 promise 的范围,但我不知道如何做。知道怎么做吗?

无论您使用什么库,都无法更改箭头函数的上下文。

var x = 5;
var f = ()=> this.x;

f();             //=> 5
f.call({x:3});   //=> 5
z.bind({x:3})(); //=> 5

因此,正如其他人评论的那样,在您发布的代码中,this 将引用 MyClass 的实例。没有什么可以改变这一点。