Cannot call a method within a class it defined it in ES6 in Node.js [duplicate]

家住魔仙堡 提交于 2019-12-05 01:27:21

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

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

When you pass create method as method it is probably called in different context (this) as you expect. You can bind it:

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

There are many other ways how to ensure this refers to correct object.

E.g. wrap it with function (either arrow or classical):

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

Or bind methods in constructor:

constructor() {
    this.create = this.create.bind(this);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!