Mithun Das
Mithun Das

Reputation: 180

es6 class cannot read property of this

Here is my code

class ModuleController {

  constructor() {
    this.testVar = 'XYZ';
  }

  create(req, res, next) {
    debug(this.testVar);
  }
}
export default ModuleController;

I get Cannot read property 'create' of undefined Why?

This is node 7 with Babel and Express -- all latest version.

Upvotes: 0

Views: 984

Answers (1)

Mithun Das
Mithun Das

Reputation: 180

For all those who have minimal knowledge ES6 classes and their use and come up here with this kind of a problem... As the others said in the comments --- the way I am calling the class method was faulty... Initially I did..

Module = new ModuleController(); 
const router = express.Router(); 
router.route('/').post(Module.create);

Which is obviously wrong... the correct way is:-

Module = new ModuleController(); 
const router = express.Router(); 
router.route('/').post((req, res, next) => Module.create(req, res, next));

Upvotes: 1

Related Questions