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:
Can somebody explain what this means, and why it works like this? What is the exact difference between the two cases?