I am experimenting with this and arrow functions. Ran into some trouble regarding the lexical scope of arrow function in setTimeout.
The makeSound method returns this as the dog object. Why does it not take the scope of the global object since the arrow function is inside the setTimeout method? Interestingly, the whatIsThis method returns the Timeout object and not the global object. I am confused on this as well.
const dog = {
name: 'fluffy',
type: 'dog',
sound: 'woof!',
makeSound: function() {
setTimeout(() => {
console.log("makeSound", this)
}, 1000)
},
whatIsThis: function() {
setTimeout(function() {
console.log("whatisthis", this)
}, 1000)
}
}
dog.makeSound() // returns dog obj
dog.whatIsThis() // returns Timeout obj
setTimeout(() => {
console.log("global", this)
}, 1000) // returns global obj