On the problem of this pointing in the ES6 arrow function, and call

when reading teacher Ruan Yifeng"s ES6 tutorial, in the arrow function chapter, in the section on this pointing, there is such an example

function foo() {
    setTimeout( () => {
        console.log("this.id:",this.id);
    },100);
}

var id = 21;

foo({ id: 42});             // 21
foo.call({ id: 42});        // 42

at this time, the output id is 21, which is

pointing to window.

so I"m a little confused about this example, which should be used to illustrate that the this direction here is changed by the arrow function, but as far as I understand it, it feels like it is changed by the call function.

because I have never been particularly clear about where this points to me, I think there is a misunderstanding of where I should be. I have tried to check the relevant knowledge points, but I still can"t figure it out. I hope someone can explain this example 0.0

.
Jan.24,2022

first of all, regardless of the arrow function, let's assume that there is a normal function in setTimeout, and the foo function looks like this:

function foo() {
    console.log('this.id:',this.id); // this.id: 42
    setTimeout( function () {
        console.log('this.id:',this.id); // this.id: 21
    },100);
}
After

executes foo.call ({id: 42}), the first line outputs 42, while setTimeout outputs 21. The first line of
outputs 42 because the call function changes the pointer execution of foo, pointing to {id: 42}

the reason why the second line outputs 21 is because setTimeout is mounted under window. SetTimeout actually changes the pointer to this, pointing this to window. So output 21.

< hr >

and after changing to the arrow function, the foo function is as follows

function foo() {
    console.log('this.id:',this.id); // this.id: 42
    setTimeout( () => {
        console.log('this.id:',this.id); // this.id: 42
    },100);
}
After

executes foo.call ({id: 42}), why does it still output 42 in setTimeout? because the arrow function causes this to always point to the object where the function definition takes effect (in this case, {id: 42}), so 42 is output.

Menu