bruce_wayne bruce_wayne - 1 year ago 57
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(; gives me undefined why?.

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

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

var myInstance = new MyClass();

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

Answer Source

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;

You can do { 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`

Loose function call

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

Using apply or call

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