2015-05-27 23 views
2

我知道在Javascript對象中,this關鍵字不是由聲明定義的,而是通過調用來定義的。所以,我想知道我們如何能避免以下問題:使用promise和'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(); 
}); 

唯一的解決辦法?

回答