从构造函数返回 ES6 promise - 绑定 this

returning ES6 promise from constructor - binding this

我想做

X.prototype.f = function() {
    return new Promise(
        function(resolve, reject) {
           if (this.f1()==0) resolve();
           ...

然而 this(即 X 实例)未在 promise 构造函数中定义。我知道我需要以某种方式绑定它,但不确定如何继续?

您可以将其赋值给函数内的另一个变量

X.prototype.f = function() {
    var self = this;
    return new Promise(
        function(resolve, reject) {
           if (self.f1()==0) resolve();
           ...

你用的是es6,为什么不用es6?

X.prototype.f = function() {
    return new Promise((resolve, reject) => {
       if (this.f1()==0) resolve();
    });
}