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?