0

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.

  • 1
    In your first example, you see `1` twice because the arrow function closes over the `this` that's current for the call to `arrowLogger`, which is set to `example` by how you called `arrowLogger`: `example.arrowLogger()`. So `this.prop` is `example.prop` is `1`. In your second example, you get different outputs because `this` inside the timer callback is **different**, since arrow functions close over `this` and traditional functions don't (they have their `this` set by how they're called). So `arrowLogger`'s callback uses `this = example`, but `simpleLogger`'s callback sees the global `this`. – T.J. Crowder Feb 06 '21 at 16:44
  • (Side note: In modern environments, including recent versions of Node.js, you can use the standard `globalThis` rather than the Node.js-specific `global` [which, sadly, wasn't web safe to add to the standard].) – T.J. Crowder Feb 06 '21 at 16:45
  • FWIW, I go into this in some detail in Chapter 3 of my recent book, *JavaScript: The New Toys*. Links in my profile if you're interested. – T.J. Crowder Feb 06 '21 at 16:47
  • I'm disappearing for a bit, but please feel free to post comments with follow-up questions, I'll be happy to clear up any remaining questions you have. :-) – T.J. Crowder Feb 06 '21 at 16:47

0 Answers0