Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

149
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda