使用承诺和 'this' 上下文调用对象方法

Calling object methods with promises and the 'this' context

我了解到在 Javascript 个对象中, this 关键字不是通过声明定义的,而是通过调用定义的。所以我想知道我们如何才能避免以下问题:

var testObject = function(){
    this.foo = "foo!";
};

testObject.prototype.sayFoo = function() {
    console.log(this.foo);
};

var test = new testObject();
test.sayFoo(); //Prints "!foo"

new Promise(function(resolve, reject){
    resolve();
}).then(test.sayFoo); //Unhandled rejection TypeError: Cannot read property 'foo' of undefined

是:

new Promise(function(resolve, reject){
    resolve();
}).then(function(){
    test.sayFoo();
});

唯一的解决办法?

不,您也可以使用 bind method

Promise.resolve().then(test.sayFoo.bind(test));

另请参阅 How to access the correct `this` context inside a callback? 了解一般问题。

但是,Bluebird does offer调用方法的额外方法:

Promise.resolve().bind(test).then(test.sayFoo);