Search code examples
javascriptnode.jsmodulethis

java script how to access function within the same module when this doesn't point to the module instead points to the global scope


When calling a function in the module in this way

app.get("/api/sessions/oauth/google", (req, res) => {
  return google_callback.googleOAuthHandler(req, res);
});

this points to the module and another function in the module can be accessed using this

googleOAuthHandler : async function (req, res) {
  const code = req.query.code.toString();
  const {id_token, access_token} = await this.getGoogleOAuthToken(code);
}

However passing the function as a parameter changes this to global and this.getGoogleOAuthToken becomes undefined i.e when doing

app.get("/api/sessions/oauth/google", google_callback.googleOAuthHandler);

how would i access getGoogleOAuthToken in googleOAuthHandler in google_callback module when using this way


Solution

  • app.get("/api/sessions/oauth/google", google_callback.googleOAuthHandler);
    

    When passing function this way this doesn't mean the module. So this.getGoogleOAuthToken doesn't work.

    however we can use module.exports.getGoogleOAuthToken to access the function within the same module. Using module.exports.getGoogleOAuthToken also works in the first example.

    Alternatively if you don't like module.exports to call the function you can place line const _this = this; at the top of the file or const _this = module.exports = { ... } and use _this.function to call a function inside the module.

    Also just noticed that in the first example this.function only works because i'm using this syntax.

    module.exports = {
      func1 : function(){},
      func2 : function(){}
    }
    

    when exporting with

    module.exports.func1 = function(){}
    module.exports.func2 = function(){}
    

    this cannot be used to access the other function