调用带有promise和'this'上下文

Calling object methods with promises and the 'this' context

本文关键字:this 上下文 promise 调用      更新时间:2023-09-26

我知道在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方法:

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

参见如何在回调中访问正确的' this '上下文?对于一般问题。

然而,Bluebird确实提供了一种额外的方法来调用该方法:

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