Reputation: 357
I can get a callback function on an instance to work in a pure Typescript project. When I try to do the same thing in a Node project using Typescript, when I refer to this, it no longer points to my instance. Is Node causing this issue, or am I missing something else. I am new to Node and we are trying to figure this out for a new project.
Example: (I moved some of the code around to simplify the example)
server.ts:
import controller = require('./controllers/locationController');
var locationController = new controller.LocationController(LocationModel.repository);
var unbound = locationController.test;
unbound(); --when this calls locationController.test, that test method no longer has access to anything on this
locationController.ts:
export class LocationController {
private _x = 1;
_repository: mongoose.Model<locationModel.ILocation>;
constructor(repository: mongoose.Model<locationModel.ILocation>) {
this._repository = repository;
}
test = () => {
var t = this._x; --This is where the issue is. _x is undefined even though I am using the arrow notation
}
}
Upvotes: 0
Views: 136
Reputation: 276269
Is Node causing this issue, or am I missing something else
Your understanding of arrow
and this
are correct. Therefore the code you have provided works fine:
The error exists in some other piece of code. Track that down.
Upvotes: 1