Reputation:
I have the following block of code to store the correct reference to this
.
I am using Mongoose for Models.Image
.
class some {
public one() {
var self = this;
this.another(); //edited: this.another() is not a function
Models.Image.findById(id).then(function(data) {
self.another(); //self.another is not a function
....
});
}
public another() {
....
}
}
The linter is showing self
to be this
but when I execute it, gives me error. What is happening here? How to solve it?
The class is a route handler bound to express routes.
I would like to add more. Calling this.another()
within the one()
(not callback) is still giving me is not a function
error. Somehow, this
is not referencing the class.
What may be the problem?
Upvotes: 0
Views: 5440
Reputation: 2623
another() is expected to be within public one() :
class some {
public one() {
var self = this;
Models.Image.findById(id).then(function(data) {
self.another(); //self.another is not a function
....
});
}
public another() {
....
}
}
Maybe better like this:
class some {
public one() {
var self = this;
Models.Image.findById(id).then(function(data) {
self.another(); //self.another is not a function
....
});
another() {
....
}
}
}
Upvotes: -3
Reputation: 23692
Edited: The class is a route handler bound to express routes.
Probably the problem is here.
Because of how the method one
is called, this
is not bound to an instance of the class some
. The issue is not about the callback. At the first line of one
, this
already has a wrong value:
var self = this; // self has a wrong value because this has a wrong value
Upvotes: 4