Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
121
rated 0 times [  123] [ 2]  / answers: 1 / hits: 86767  / 9 Years ago, thu, january 21, 2016, 12:00:00

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?


More From » node.js

 Answers
4

this is always the object the method is called on. However, when passing the method to then(), you are not calling it! The method will be stored somewhere and called from there later. If you want to preserve this, you will have to do it like this:



.then(() => this.method2())


or if you have to do it the pre-ES6 way, you need to preserve this before:



var that = this;
// ...
.then(function() { that.method2() })

[#63623] Tuesday, January 19, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
isham

Total Points: 69
Total Questions: 86
Total Answers: 86

Location: Anguilla
Member since Sun, Jan 29, 2023
1 Year ago
;