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

115
Vistas
Cannot redefine property when trying change property of a global variable

How can we set custom getter/setter on already existing global variable? A straightforward approach fails:

var myVar;

{
  let _myVar = myVar;
  delete myVar;
  Object.defineProperty(window, "myVar", {
    get()
    {
      return _myVar;
    },
    set(val)
    {
      _myVar = val;
    }
  });
}

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

var myVar;

According to this document:

Any property declared with var cannot be deleted from the global scope or from a function's scope.

Therefore, delete myVar won't get applied, and that's why you cannot set a value again for myVar with defineProperty.

For a simple test, you can try to log myVar value after delete myVar.

var myVar = 5; //set a value for `myVar`

{
  let _myVar = myVar;
  delete myVar; //delete `myVar`
  console.log(myVar); //it's still 5
  Object.defineProperty(window, "myVar", {
    get()
    {
      return _myVar;
    },
    set(val)
    {
      _myVar = val;
    }
  });
}

For a potential solution, you can explicitly set a property to window object which is considered as a global variable.

window.myVar = 5; //set a value for `window.myVar`

{
  let _myVar = window.myVar;
  delete window.myVar;
  console.log(window.myVar); //`undefined` as expected
  Object.defineProperty(window, "myVar", {
    get() {
      return _myVar;
    },
    set(val) {
      _myVar = val;
    }
  });
}

Just one side note that in terms of global variable usage, var and window are not different. You can declare window.myVar, but you can use myVar (without window) directly.

window.myVar = 5; //set a value for `window.myVar`

{
  let _myVar = myVar;
  delete window.myVar;
  console.log(window.myVar); //`undefined` as expected
  Object.defineProperty(window, "myVar", {
    get() {
      return _myVar;
    },
    set(val) {
      _myVar = val;
    }
  });
  console.log(myVar); //set it again with `defineProperty`
}

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