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 ?
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With