据我了解,在 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);
关于javascript - 使用 Promise 和 'this' 上下文调用对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30490679/