Node.js 这在NodeJS中没有定义

Node.js 这在NodeJS中没有定义,node.js,ecmascript-6,Node.js,Ecmascript 6,这是我的route.js文件,它处理所有路由 // Import post controller const PostController = require('../controllers/post'); // Call post controller for API router.post('/posts', PostController.create); 然后控制器中有post.js文件,它导出post类 const PostModel = require('../models/pos

这是我的route.js文件,它处理所有路由

// Import post controller
const PostController = require('../controllers/post');

// Call post controller for API
router.post('/posts', PostController.create);
然后控制器中有post.js文件,它导出post类

const PostModel = require('../models/post');

class Post 
{
    async create ()
    {
        response = {};

        let posts = await PostModel.find({});

        response.additionalInfo = this.getAdditionalInfo();

        res.status(200).send({response});
    }

    getAdditionalInfo ()
    {
        // returns some data for users and something
    }
}

module.exports = new Post();
现在我的问题是如何从create方法调用
getAdditionalInfo()
?因为如果我尝试
this.getAdditionalInfo()
我会得到
undefined
错误

这就是
create
的使用方式:

router.post('/posts', PostController.create);
用你的

router.post('/posts', PostController.create);
router.post
正在接受名为
create
的函数作为回调。这意味着当调用它时,例如,如果
router.post
的内部代码如下所示:

(url, callback) => {
  on(someevent, () => {
    callback();
  });
}
缺少调用上下文。它没有调用
PostController.create()
,它只是调用
someCallbackVariableName()
。因此,在没有调用上下文的情况下,
create
内部的
this
因此是
undefined

相反,可以传递一个调用
create
的函数,该函数使用适当的调用上下文:

router.post('/posts', () => PostController.create());
或者使用
.bind
将调用上下文显式设置为
PostController

router.post('/posts', PostController.create.bind(PostController));

I get:-无效状态代码:TypeError:无法读取未定义的属性“getAdditionalInfo”,因为
未定义。router.post('/posts',PostController.create);无需使用此关键字,只需调用getAdditionalInfo()并进行检查。@Sudharshan,然后我得到:-无效状态代码:ReferenceError:getAdditionalInfo未定义您没有定义构造函数方法,因此解释器替换了默认方法,而默认方法不起任何作用。非常感谢您如此轻松地解释它。:)在本例中,我们将如何使用参数?outer.post('/posts',PostController.create(param1.bind(PostController))@johnktejik传递一个函数,该函数使用正确的参数调用
。create
<代码>路由器.post('/posts',()=>PostController.create(param1))