Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!