我正在使用Node.js,Express.js和MongoDB制作应用程序.我正在使用MVC模式,并且还有单独的路由文件.我正在尝试创建一个Controller类,其中一个方法调用在其中声明的另一个方法.但我似乎无法做到这一点.我得到"无法读取未定义的属性".
index.js文件
let express = require('express');
let app = express();
let productController = require('../controllers/ProductController');
app.post('/product', productController.create);
http.createServer(app).listen('3000');
Run Code Online (Sandbox Code Playgroud)
ProductController.js文件
class ProductController {
constructor(){}
create(){
console.log('Checking if the following logs:');
this.callme();
}
callme(){
console.log('yes');
}
}
module.exports = new ProductController();
Run Code Online (Sandbox Code Playgroud)
当我运行这个时,我收到以下错误消息:
Cannot read property 'callme' of undefined
Run Code Online (Sandbox Code Playgroud)
我已经运行了这个代码,只需要进行一些修改,如下所示,它可以工作.
class ProductController {
constructor(){}
create(){
console.log('Checking if the following logs:');
this.callme();
}
callme(){
console.log('yes');
}
}
let product = new ProductController();
product.create();
Run Code Online (Sandbox Code Playgroud)
为什么一个工作而另一个工作?救命!