`this` 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);

In this magazine LOG ! undefined

How can I access thisin the controller class?

+10
source share
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 maybe a little more useful when you need to link multiple methods).

+20
source

The answer above, I want to add a little to help clarify:

Suppose we have a class:

class TClass {
  constructor(arg) {
    this.arg = arg
  }
  test() {
    console.log(this.arg)
  }
}

This will NOT work:

const t = new TClass("test")
const method = t.test  // method is simply a reference without context
method() // 'this' is not defined

This will work:

const t = new TClass("test")
t.test() // log 'test'

And the reason is because the comments above, the function link has no context

0

Source: https://habr.com/ru/post/1623443/


All Articles