0

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
    }
}

1 Answer 1

1

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:

enter image description here

Solution

The error exists in some other piece of code. Track that down.

1
  • Thanks basarat. It looks like part of my issue was that I am using visual studio, and I was setting a breakpoint on this._x. When I hovered over it, it said undefined, but when I ran past it, I can see that it actually sets var t correctly. I know I was hitting an error at some point on Friday, but it looks like it is fine know, and I was just being thrown off by the undefined value that shows on hover.
    – Ryan
    Commented Jun 29, 2015 at 17:44

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.