Home > Blockchain >  Arrow function is undefined in extended calass
Arrow function is undefined in extended calass

Time:06-09

I have a class, and another class that extends the fist one. In my code I create a new instance of the extended class: new MyCustomEndpoint(router);

the problem is that handleIsNotOk is undefined in initMyRoutes

export class MyEndpoint {
    constructor(router: express.Router) {
        this.initMyRoutes(router); 
    }

    protected initMyRoutes(router: express.Router) {
        router.get(`/v1/isok`, this.handleIsOk);
    }

    protected handleIsOk = (req: express.Request, res: express.Response) => {
        res.send(200);
    }
}


export class MyCustomEndpoint extends MyEndpoint{
    private test = "Test";

    protected initMyRoutes(router: express.Router) {
        console.log(this.handleIsNotOk); // undefined
        console.log(this.handleIsNotOkFn);

        router.get(`/v1/isokcustom`, this.handleOk); // this works
        router.get(`/v1/isnotok`,this.handleIsNotOk); // this doesn't works
        router.get(`/v1/isnotokfn`, this.handleIsNotOkFn); // this doesn't works
        router.get(`/v1/isnotokfn`, (req, res)this.handleIsNotOkFn(req,res)); // works but it's ugly since it's different compared to router.get(`/v1/isokcustom`, this.handleOk);
    }

    protected handleIsNotOk = (req: express.Request, res: express.Response) => {
        res.send(200);
    }

    protected handleIsNotOkFn(req: express.Request, res: express.Response){
        console.log(this.test); // undefined
        res.send(200);
    }
}

...

new MyCustomEndpoint(router);

why is this happening? should not be undefined in my opinion

CodePudding user response:

I bet this is the reason

router.get(`/v1/isnotokfn`, this.handleIsNotOkFn); 

and if you bind it to the instance, it'll work just fine:

router.get(`/v1/isnotokfn`, this.handleIsNotOkFn.bind(this)); 

CodePudding user response:

You overwrite initMyRoutes and you're waiting your mother class to call the new initMyRoutes. You should have a constructor in MyCustomEndPoint where you call initMyRoutes MyCustomEndPoint never calls initMyRoutes

  • Related