据我所知,在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();
});
唯一的解决方案?
答案 0 :(得分:3)
不,您也可以使用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);