2

I understand that in Javascript objects, the this keyword is not defined by declaration, but by invocation. So I am wondering how we can avoid the following problem:

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

Is:

new Promise(function(resolve, reject){
    resolve();
}).then(function(){
    test.sayFoo();
});

the only solution?

Nepoxx
  • 4,849
  • 5
  • 42
  • 61

1 Answers1

3

No, you can use the bind method as well:

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

See also How to access the correct `this` context inside a callback? for the generic problem.

However, Bluebird does offer an extra way to call the method:

Promise.resolve().bind(test).then(test.sayFoo);
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375