I have a javascript class, and each method returns a Q
promise. I want to know why this
is undefined in method2
and method3
. Is there a more correct way to write this code?
function MyClass(opts){
this.options = opts;
return this.method1()
.then(this.method2)
.then(this.method3);
}
MyClass.prototype.method1 = function(){
// ...q stuff...
console.log(this.options); // logs "opts" object
return deferred.promise;
};
MyClass.prototype.method2 = function(method1resolve){
// ...q stuff...
console.log(this); // logs undefined
return deferred.promise;
};
MyClass.prototype.method3 = function(method2resolve){
// ...q stuff...
console.log(this); // logs undefined
return deferred.promise;
};
I can fix this by using bind
:
function MyClass(opts){
this.options = opts;
return this.method1()
.then(this.method2.bind(this))
.then(this.method3.bind(this));
}
But not entirely sure why bind
is necessary; is .then()
killing this
off?
this
. – BlasesetTimeout
issue; as the problem arises in two completely different ways. People looking to resolve theirthis
scoping issues in the context of promises are immediately being pointed to a more indirect question, where the accepted answer uses anti-patterns from 2009.2 + 2 = 4
!==((8+2)*6)/15 = 4
– Pyorrhea