0

Pretty straight forward code. I am importing a class, instantiating it with some values and calling a method on it. When the method is called, I'm expecting it to make use of the initialized values I passed it earlier.

However, when I'm in the instance method, I'm getting this as undefined.

The specific error that I'm getting in this case: Cannot read property 'model' of undefined

const utilities = require('../../components/utilities');

class BaseController {
  constructor(model) {
    this.model = model;
  }

  show(req, res) {
    return this.model.query()
      .findById(req.params.id)
      .then(item => {
        if (!item) return utilities.throwNotFonud(res);
        return utilities.responseHandler(null, res, 200, item);
      })
    .catch(err => utilities.responseHandler(err, res));
  }
}

module.exports = BaseController;
const express = require('express');
const BaseController = require('../core/base.controller');
const Category = require('./category.model');

const controller = new BaseController(Category);
const router = express.Router();

router.get('/:id', controller.show);

module.exports = router;
deceze
  • 471,072
  • 76
  • 664
  • 811
Sayem
  • 5,939
  • 4
  • 20
  • 22
  • 2
    You need to bind the context if you're passing the function as callback: `router.get('/:id', controller.show.bind(controller))` – deceze Aug 11 '16 at 10:51
  • Just curious why would I need to bind the context if I'm calling an instance of a class? Doesn't it already have it's context since it's an instance? – Sayem Aug 11 '16 at 10:55
  • 4
    You're not *calling* the method, you're passing a function to another function. That divorces it from its context. The `this` context is established **at call time** and depends on *how you call* the function. – deceze Aug 11 '16 at 10:56
  • Ah that makes sense! Thank you. – Sayem Aug 11 '16 at 10:57

0 Answers0