0

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.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
Mithun Das
  • 181
  • 2
  • 6
  • Java isn't JavaScript. – GhostCat Aug 15 '17 at 16:56
  • 2
    Depends on how `create` is called. – Dave Newton Aug 15 '17 at 16:57
  • works for me at http://ideone.com/OntsxO – marvel308 Aug 15 '17 at 17:01
  • The code you posted doesn't even use `create` anywhere. Show us how you call the class. – Bergi Aug 15 '17 at 17:10
  • In JavaScript, `this` refers to the current context, nothing more. I suspect you are calling `create()` with some kind of closure being utilized, so `this` has different execution context than you expect. – agm1984 Aug 15 '17 at 17:27
  • @Bergi --- here's how I call it:- `const Module = new ModuleController(); const router = express.Router(); router.route('/').post(Module.create); // we assume when we call a function router invokes req, res, next into it.` – Mithun Das Aug 16 '17 at 01:45
  • @agm1984 and others --- you guys are absolutely right. My call of the function is wrong. It should be called as `router.route('/')..post((req, res, next) => Module.create(req, res, next));` – Mithun Das Aug 16 '17 at 01:56
  • @MithunDas Yes, that's the problem. See [How to access the correct `this` / context inside a callback?](https://stackoverflow.com/q/20279484/1048572) – Bergi Aug 16 '17 at 01:56
  • @Bergi just solved it, see my comments – Mithun Das Aug 16 '17 at 01:57
  • 1
    Thank you all... its really nice to hear from you guys :) – Mithun Das Aug 16 '17 at 01:58
  • If you encounter similar later on, investigate `.bind()`. You can bind to another object's context. I personally consider that pretty dirty however in node.js, unless you are making a bound/exotic function. – agm1984 Aug 16 '17 at 03:44

1 Answers1

1

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));
Mithun Das
  • 181
  • 2
  • 6