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

197
Visualizações
Binding objects to functions in Javascript
let user = {
  firstName: "John",
  sayHi() {
    alert(`Hello, ${this.firstName}!`);
  }
};

let sayHi = user.sayHi.bind(user); 

sayHi(); // Hello, John!

setTimeout(sayHi, 1000); // Hello, John!

// even if the value of user changes within 1 second
// sayHi uses the pre-bound value which is reference to the old user object
user = {
  sayHi() { alert("Another user in setTimeout!"); }
};

Why this weird behaviour ? If i change the value of method shouldn't it just use the changed value . How does it obtain user in lexical environment ?

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

0

You're conflating variables and objects.

After this...

let user = {
  firstName: "John",
  sayHi() {
    alert(`Hello, ${this.firstName}!`);
  }
};

You have a variable called user, containing an object. But the object is not the variable, and the variable is not the object. If you were to run user = null, the object would still exist, until garbage collected.

Next, you run

let sayHi = user.sayHi.bind(user); 

Now you have another variable, containing a bound function. The function is bound to the object currently sitting in user, but it has nothing to do with the user variable, except that you can still reach through that variable to manipulate the object (ie user.firstName = "bob"). The variable still points to the object created above.

At this point, you could run user = null and the function sayHi would still have a function, still bound to the object, which will no longer be garbage collected because there is an active reference to it. You're reassigning the variable, but not removing/replacing the object to which it points.

Later, when you run this...

user = {
  sayHi() { alert("Another user in setTimeout!"); }
};

This is no different than running user = null. The variable sayHi still holds the old function, still bound to the old object. The variable user is no longer relevant to the variable sayHi in any way. They contain two unrelated objects.

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