不能调用它在Node.js中的ES6中定义的方法 [英] Cannot call a method within a class it defined it in ES6 in Node.js
问题描述
我正在使用Node.js,Express.js和MongoDB制作应用程序。
我正在使用MVC模式,并且还有路由的单独文件。
我正在尝试我做一个Controller类,其中一个方法调用在其中声明的另一个方法。但我似乎无法做到这一点。我得到无法读取属性的未定义。
I am making an app using Node.js, Express.js and MongoDB. I am using a MVC pattern and also have separate file for routes. I am trying me make a Controller class, in which a method calls another method declared within it. But I cannot seem to be able to do this. I get "Cannot read property '' of undefined".
index.js文件
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文件
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 run this I get following error message:
Cannot read property 'callme' of undefined
我已经运行了这个代码,没有什么修改,如下所示,它的工作原理。
I have ran this code by itself with little modification as following 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();
为什么一个工作而不是另一个?
HELP!
Why does one work and not the other? HELP!
推荐答案
您的方法是被反弹到快递内的层
类,失去原来上下文。快递处理路由的方法是将每个路径包裹在一个层
类中,该类将路由回调分配给自己:
Your method is being rebound to the Layer
class within express, losing its original context. The way that express handles routes is by wrapping each one in a Layer
class, which assigns the route callback to itself:
this.handle = fn;
这是您的问题出现的地方,此作业自动将功能上下文重新绑定到层
。以下是一个简单的示例演示问题:
That is where your problems arise, this assignment automatically rebinds the function context to Layer
. Here is a simple example demonstrating the problem:
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
其他人已经指出了解决方案,这是明确绑定你的方法到 ProductController
实例:
Others have already pointed out the solution, which is to explicitly bind your method to the ProductController
instance:
app.post('/product', productController.create.bind(productController));
这篇关于不能调用它在Node.js中的ES6中定义的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!