【发布时间】:2016-09-21 16:24:31
【问题描述】:
我正在使用 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');
ProductController.js 文件
class ProductController {
constructor(){}
create(){
console.log('Checking if the following logs:');
this.callme();
}
callme(){
console.log('yes');
}
}
module.exports = new ProductController();
当我运行它时,我收到以下错误消息:
Cannot read property 'callme' of undefined
我自己运行了这段代码,几乎没有如下修改,它可以工作。
class ProductController {
constructor(){}
create(){
console.log('Checking if the following logs:');
this.callme();
}
callme(){
console.log('yes');
}
}
let product = new ProductController();
product.create();
为什么一个有效而另一个无效? 帮助!
【问题讨论】:
-
你应该never export a class instance。要么导出类本身,要么只使用一个对象。
-
您应该使用属性初始化语法(
callme = () => {...}而不是像这样的callme() {...})在类中定义方法。 github.com/facebook/flow/issues/5874#issuecomment-369922816
标签: javascript node.js express ecmascript-6 es6-class