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

223
Visualizações
Javascript arrow function weird behaviour with "this" keyword

This arrow function prints the concatenated string version of the array correctly:

var tahoe = {
  resorts: ["Kirkwood","Squaw","Alpine","Heavenly","Northstar"],
  print: function(delay=1000) {

    setTimeout(
      () => console.log(this.resorts.join(",")),
      delay
    )

  }
}

tahoe.print()

If I understand correctly, if I use a normal function inside the setTimeout, it will not work, because setTimeout requires a nested function that is aways evaluated in the global scope, while the array is defined within the scope of the object. So the arrow function is used which works in the scope of the object.

Then, how come putting the print function as arrow function as well reverses the problem again?

var tahoe = {
  resorts: ["Kirkwood","Squaw","Alpine","Heavenly","Northstar"],
  print: (delay=1000) => {

    setTimeout(() => {
      console.log(this.resorts.join(","))
    }, delay)

  }
}

tahoe.print()

This doesn't work. The book explains it like this:

enter image description here enter image description here

Can somebody explain what this means, and why it works like this? What is the exact difference between the two cases?

about 4 years ago · Juan Pablo Isaza
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