I try to understand the difference between this in the manner of arrow functions and ordinary ones. However, every time it seems that I got the idea, something is missing, so I started to clean the air a little bit, and found out this, and after coding around for a while, I got this difference.
class Func {
constructor(name) {
this.prop = name;
}
arrowLogger(){
let self = (() => {
return this.prop;
})();
console.log(self);
}
simpleLogger(){
console.log(this.prop);
}
}
let example = new Func(1);
global.prop = 2;
console.log(example.arrowLogger());
console.log(example.simpleLogger())
why do 2 console.log s print the same number?
And why is it not the same answer in the following piece?
class Func {
constructor(name) {
this.prop = name;
}
arrowLogger(){
setTimeout(() => {
console.log("arrow this:")
console.log(this)
console.log("arrow:",this.prop);
}, 0)
}
simpleLogger(){
setTimeout( function (){
console.log("simple this:")
console.log(this)
console.log("simple:" , this.prop)
} , 0)
}
}
let example = new Func(1);
global.prop = 2;
console.log(example.arrowLogger());
console.log(example.simpleLogger())
P.S. I used <> as I wrote this in Node.js.