【问题标题】:Calling object methods with promises and the 'this' context [duplicate]使用承诺和“this”上下文调用对象方法[重复]
【发布时间】:2015-08-10 00:34:31
【问题描述】:

我了解在 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();
});

唯一的解决方案?

【问题讨论】:

    标签: javascript bluebird


    【解决方案1】:

    不,您也可以使用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);
    

    【讨论】:

      猜你喜欢
      • 2019-04-26
      • 1970-01-01
      • 2013-10-16
      • 2014-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多