在Node.js的ES6中定义它的类中不能调用一个方法

我正在使用Node.js,Express.js和MongoDB制作应用程序。 我正在使用MVC模式,也有单独的路由文件。 我想我做一个控制器类,其中一个方法调用其中声明的另一个方法。 但我似乎无法做到这一点。 我得到“无法读取未定义的属性”。

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(); 

为什么一个工作,而不是另一个? 帮帮我!

你的方法正在被反弹到Layer类内的快递 ,失去了原来的上下文。 expression式处理路由的方法是将每一个包装在一个Layer类中,该类将路由callback分配给自己:

 this.handle = fn; 

这就是你的问题出现的地方,这个任务会自动将函数上下文重新绑定到Layer 。 下面是一个简单的例子,展示了这个问题:

 function Example() { this.message = "I have my own scope"; } Example.prototype.logThis = function() { console.log(this); } function ReassignedScope(logThisFn) { this.message = "This is my scope now"; // simulation of what is happening within Express's Layer this.logThis = logThisFn; } let example = new Example() let scopeProblem = new ReassignedScope(example.logThis); scopeProblem.logThis(); // This is my scope now 

其他人已经指出了解决scheme,即将您的方法显式绑定到ProductController实例:

 app.post('/product', productController.create.bind(productController)); 

当您将create方法作为方法传递时,可能会按照您的预期在不同的上下文中调用它( this )。 你可以绑定它:

 app.post('/product', productController.create.bind(productController)); 

还有很多其他的方法来确保this指的是正确的对象。

例如用function(箭头或古典)包装它:

 app.post('/product', (...args) => productController.create(...args)); 

或者在构造函数中绑定方法:

 constructor() { this.create = this.create.bind(this); }