Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

152
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda