0

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?

SexyBeast
  • 7,303
  • 27
  • 100
  • 185
  • 1
    _“`setTimeout` requires a nested function that is aways evaluated in the global scope”_ — That’s wrong. The function is evaluated in the same scope. You’re confusing scope with `this` binding here. `setTimeout`’s callback function is called without any `this` binding. _“The book explains it like this”_ — I don’t know which book this is, but please read the answer under the linked post “How does the ‘this’ keyword work?” which offers the most thorough and up-to-date description of how `this` works. – Sebastian Simon Dec 20 '21 at 21:39

0 Answers0