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

151
Visualizações
Do objects have access to outer Lexical Environment?

I was trying to find a solution for counter(i) function of JS fun practice, and I ended up with this:

function counter(start) {
  let count = start;
  return {
    up() {
      return ++count;
    },
    down() {
      return --count;
    },
  }
}

let obj = counter(10);
let {up, down} = obj;

console.log(up()); // 11
console.log(down()); // 10
console.log(down()); // 9
console.log(up()); // 10
At the first sight I thought there would be an error because objects don't have Lexical Environment. I thought neither up() nor down() would be able to access count. But when I tried to run the code, it worked!
I know how Lexical Environment works, and I wonder if there is a way for objects to access it.
When counter function returns the object there should be a link between the object and its Lexical Environment so that up() and down() can access count. Is there anything like that?

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

0

I know how Lexical Environment works, and I wonder if there is a way for objects to access it. When counter function returns the object there should be a link between the object and its Lexical Environment so that up() and down() can access count. Is there anything like that?

Yes. Javascript supports 3 types of scopes:

  1. Global
  2. Function
  3. Block

Anything within a pair of curly braces ( {...} ) forms a block in Javascript. Block scopes have their own lexical environment. So the object returned from counter() is a block which has reference to counter()'s lexical environment using which it can access the count variable.

The functions up() and down() form a closure and hence can access count even when invoked from global i.e. outside of counter()'s scope.

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