byCedric
byCedric

Reputation: 21

Babel/ES6 extended class methods undefined

Currently I'm using Babel to write a Node.js backend in ES6. Unfortunately I encountered a strange behaviour when extending a specific class. Some of my methods, defined in the extending class, are undefined. Unless I use the ES7 syntax to bind them to a property.

This is the actual code that gives me this strange behaviour:

import { Router } from 'express';

class MyCustomRouter extends Router
{
    constructor() {
        super();

        this.methodWorks();  // works like a charm.
        this.methodDoesnt(); // throws TypeError: _this.methodDoesnt is not a function
    }

    methodWorks = () => {
        // some content
    }

    methodDoesnt() {
        // some content
    }
}

This is actually extends the Router from the expressjs library. So right now I'm just curious if someone could explain this behaviour and/or if there is a way to fix this.

Upvotes: 0

Views: 305

Answers (1)

byCedric
byCedric

Reputation: 21

I went looking inside the code of ExpressJS itself to find some explanation. Apparently they like to return a whole new and different context from the Router's constructor. Which explains why this is totally different and not containing my methods...

Upvotes: 2

Related Questions