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

前端 未结 1 1563
余生分开走
余生分开走 2021-01-25 00:36

Nb. This is driving me a little nuts and I\'ve been around the houses a few times. However I\'m fairly new to ES6 and JS as a whole and fully understand that a

相关标签:
1条回答
  • 2021-01-25 00:52

    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.

    0 讨论(0)
提交回复
热议问题