I'm following this tut on js: https://www.youtube.com/watch?v=ajTvmGxWQF8&list=PL1PqvM2UQiMoGNTaxFMSK2cih633lpFKP&index=8
and in the part where he explains why not to use setTimeout with arrow functions, the justification is that they look for scope on the window. and not on the enclosed scope. But the tests i made, had the opposite results: the named functions had window, arrow function was the correct one. So:
const dude = {
name: 'dude',
namedFunc() {
console.log('name 1: ', this.name); // Dude
setTimeout(function() {
console.log('this 1:', this);
console.log('name 2:', this.name); // undefined
}, 200);
},
arrowFunc() {
console.log('name 3:', this.name); // Dude
setTimeout(() => {
console.log('this 2:', this); // {name: 'dude', nameWNamed: ƒ, nameWArrow: ƒ}
console.log('name 4:', this.name); // Dude
}, 300)
}
}
console.log('namedFunc:', dude.namedFunc()); // Dude
console.log('arrowFunc:', dude.arrowFunc()); // Dude
Expected:
this 1: {name: 'dude', namedFunc: ƒ, arrowFunc: ƒ}
name 2: dude
this 2: Window {window: Window, self: Window, document: document, name: '', location: Location, …}
name 4:
Actual result:
this 1: Window {window: Window, self: Window, document: document, name: '', location: Location, …}
name 2:
this 2: {name: 'dude', namedFunc: ƒ, arrowFunc: ƒ}
name 4: dude