Javascript 使用承诺和';这';上下文

Javascript 使用承诺和';这';上下文,javascript,bluebird,Javascript,Bluebird,我知道在Javascript对象中,this关键字不是通过声明定义的,而是通过调用定义的。因此,我想知道如何避免以下问题: var testObject = function(){ this.foo = "foo!"; }; testObject.prototype.sayFoo = function() { console.log(this.foo); }; var test = new testObject(); test.sayFoo(); //Prints "!foo

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

唯一的解决方案?

不,您也可以使用:

有关一般问题,请参见

但是,调用该方法的另一种方法是:

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