Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`this` is undefined in expressJS route handler

groups.js

class groupsCtrl {
  constructor() {
    this.info = "test";
  }

  get(res, req) {
    console.log("LOG ! ", JSON.stringify(this));
  }
}
module.exports = new groupsCtrl(); //singleton

routes.js

var express = require('express');
var router = express.Router();

var groupsCtrl = require('controllers/api_admin/groups.js');
router.get('/groups/', groupsCtrl.get);

This logs LOG ! undefined

How can I have access to this in my controller class ?

like image 791
IggY Avatar asked Jan 08 '16 15:01

IggY


2 Answers

You need to bind the method to the instance.

One solution:

router.get('/groups/', groupsCtrl.get.bind(groupsCtrl));

Another solution:

constructor() {
  this.info = "test";
  this.get  = this.get.bind(this);
}

Or use something like es6bindall (which basically does the same as the code above, but is perhaps a bit more useful when you need to bind more than one method).

like image 168
robertklep Avatar answered Sep 27 '22 23:09

robertklep


class groupsCtrl {
    constructor() {
        this.info = 'test';
    }

    get = (res, req) => {
        console.log('LOG ! ', JSON.stringify(this));
    };
}

You can just use arrow function to avoid boilerplate code

like image 32
Focus RS Avatar answered Sep 28 '22 00:09

Focus RS