SharadCodes SharadCodes - 3 months ago 20
TypeScript Question

self = this but cannot access self.function within a callback

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?

Answer

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