bruce_wayne bruce_wayne - 2 months ago 9
Javascript Question

Why this is not giving correct context while using promise?

I need to use Promise to execute things order in the following code. My actual save is ajax POST and want to call execute only after that successful POST.
Everything is working fine, but the problem is that I can't access the actual this variable, inside execute function. console.log(this.abc); gives me undefined why?.

function MyClass(context) {
this.abc = "xyz";
};

MyClass.prototype.save = function() {
console.log(" saving");
return new Promise(function(resolve, reject){
resolve();
});
};

MyClass.prototype.execute = function() {
console.log(" executing");
console.log(this.abc);
};

var myInstance = new MyClass();

window.addEventListener('keydown', function(e) {
e.preventDefault();
if(event.ctrlKey & (event.which==83)) {
myInstance.save();
} else if (event.ctrlKey && (event.which==69)) {
myInstance.save().then(myInstance.execute);
}
}, false);

Answer

Because you are passing a reference to a function to be executed by some other code, without specifying what to use as this.

Instead of

myInstance.save().then(myInstance.execute);

You can do

myInstance.save().then(function() { myInstance.execute() });

Because in that case you are the one calling a function using dot notation, which means that the object to the left of the dot will be used as this.

The lesson is, what matters is how the function gets called, it could be:

Dot notation

// `this` will be `a`
a.b(); 

Loose function call

//  If in strict mode, this will be null, otherwise it will be the global context
var b = a.b;
b();

Using apply or call

var b = a.b;
// Call b passing a as `this` and 1 as its argument
b.call(a, 1)