Node.js ES6 Class unable to call class method from within class method when using Express.js

亡梦爱人 提交于 2019-12-02 07:17:35

You aren't getting a proper this pointer in your method.

Change this line of code:

app.post('/api/v1/user/update', urlencodedParser, user.update);

to this:

app.post('/api/v1/user/update', urlencodedParser, user.update.bind(user));

When you pass user.update, all it passes is a reference to the update() method and the associate with the user object is lost. When Express then calls it as a normal function, this will be undefined (in strict mode) inside that method rather than your user object. You can use .bind() to solve this issue as shown above.

FYI, this has nothing specifically to do with Express. It's a generic issue when passing a reference to an obj.method as a callback that you want some code to store and then call later. You have to "bind" the object to it so that it gets called with the right object context.

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