Michael Malura Michael Malura - 7 months ago 352
Javascript Question

Nodejs, express routes as es6 classes

I want to clean up my project a bit and now i try to use es6 classes for my routes. My problem is that this is always undefined.

var express = require('express');
var app = express();

class Routes {
constructor(){
this.foo = 10
}

Root(req, res, next){
res.json({foo: this.foo}); // TypeError: Cannot read property 'foo' of undefined
}
}

var routes = new Routes();
app.get('/', routes.Root);
app.listen(8080);

Answer

try to use the code to pin this:

app.get('/', routes.Root.bind(routes));

You can get out of the boilerplate using underscore bindAll function. For example:

var _ = require('underscore');

// ..

var routes = new Routes();
_.bindAll(routes)
app.get('/', routes.Root);

I also found that es7 allows you to write the code in a more elegant way:

class Routes {
    constructor(){
        this.foo = 10
    }

    Root = (req, res, next) => {
        res.json({foo: this.foo}); // TypeError: Cannot read property 'foo' of undefined
    }
}

var routes = new Routes();
app.get('/', routes.Root);