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

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

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 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