Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This is undefined in NodeJS

SO here is my route.js file, which handles all the routes.

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

// Call post controller for API
router.post('/posts', PostController.create);

And then there is post.js file in controllers, which exports Post class.

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

Now My question is how do i call getAdditionalInfo() from create method? because if i try this.getAdditionalInfo() i get undefined error.

This is how create is being used:

router.post('/posts', PostController.create);
like image 564
pawanpandey392 Avatar asked Aug 23 '18 06:08

pawanpandey392


1 Answers

With your

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

, router.post is accepting a function named create as a callback. This means that when it's invoked, for example, if the internal code for router.post looks something like this:

(url, callback) => {
  on(someevent, () => {
    callback();
  });
}

The calling context is missing. It's not calling PostController.create(), it's just calling someCallbackVariableName(). So, without a calling context, the this inside of create is undefined as a result.

Instead, either pass a function that invokes create with the proper calling context:

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

Or use .bind to explicitly set the calling context to PostController:

router.post('/posts', PostController.create.bind(PostController));
like image 107
CertainPerformance Avatar answered Oct 22 '22 17:10

CertainPerformance