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

155
Visualizações
JavaScript define function to take outer function parameter

I want to define a function:

const f = (outside, param1, param2) => {
  outside(param1, param2);
}

But I know this function will always be called inside a function which has outside as parameter. For example:

const g = (outside, param3, param4) => {
  // some code here

  f(outside, var1, var2);

  // some more code
}

Is there any way to define f so that I dont need to pass outside to it when calling inside g?

Also I want to be able to call f inside other functions who take outside as parameter, not just g.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Is there any way to define f so that I dont need to pass outside to it when calling inside g?

No. You are asking for dynamic scope but JavaScript uses lexical scope. That means the availability/visibility of symbols is determined by the way functions are defined, not how/when/where they are called.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can change the order of the arguments and take action depending on their existence:

const f = (param1, param2, outside) => {
  if (outside) {
    outside(param1, param2);
  } else {
    ...
  }
}

UPDATE

Unfortunately a function defined outside of function g, will not have direct access to the variables contained in function g. For this reason, you must necessarily pass the parameter outside to function f.

about 4 years ago · Juan Pablo Isaza Relatório

0

And if you change your logic like this? Will it fit your needs?

// Set function logic
const f = (param1, param2) => {
  return param1 + param2;
}

// Outside method
const outside = v => {
  console.log(`I'm outside: ${v}`);
}

// Call from outside logic
const g = (outside, param3, param4) => {
  // If you know, that it is outside wrapper, wrap it here
  outside(f(param3, param4));
}
g(outside, 2, 2);

// Call from else logic
console.log(`I'm else logic: ${f(3, 3)}`);

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