I am building an application using Node.js, Express.js and MongoDB. I use the MVC pattern and also have a separate file for routes. I am trying to create a Controller class in which a method calls another method declared inside it. But I canβt do it. I get "Can't read the" undefined "property.
index.js file
let express = require('express'); let app = express(); let productController = require('../controllers/ProductController'); app.post('/product', productController.create); http.createServer(app).listen('3000');
ProductController.js File
class ProductController { constructor(){} create(){ console.log('Checking if the following logs:'); this.callme(); } callme(){ console.log('yes'); } } module.exports = new ProductController();
When I ran this, I get the following error message:
Cannot read property 'callme' of undefined
I myself ran this code with slight modifications as shown below and it works.
class ProductController { constructor(){} create(){ console.log('Checking if the following logs:'); this.callme(); } callme(){ console.log('yes'); } } let product = new ProductController(); product.create();
Why does one work and not the other? HELP!
source share