Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

41
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

7 months 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

7 months 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 job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.