Toffee Conmigo
Toffee Conmigo

Reputation: 87

Callback arrow function does not inherit 'this' from it's parent function **this is not a duplicate**

This is not a duplicate, please do not close it again.

I went through What does "this" refer to in arrow functions in ES6? but didn't find an answer.

class A{
    static myf(test){
          console.log(this); //when A.myf executes,  logs 'A'
          test();
     }
}

A.myf(()=>{
    console.log(this); // logs 'window'
})

Could someone help me with this? In the case above, the arrow function's lexical environment is A.myf, and 'this' of the arrow function should inherit from 'this' of myf. so why logs 'window' instead of A?

Upvotes: 0

Views: 310

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371089

A new Lexical Environment is created whenever another block is entered.

Blocks are delimited by {s and }s - usually seen at the beginning of functions function foo() { or at the beginning of loops for (...) { while (...) {. (Object literals are not blocks.)

You're correct when you say

As far as I know, arrow functions' 'this' inherits scope from its lexical environment.

There are 2 such environments here (which can be visualized as containers mapping identifier names to their values in that block): the environment at the top level, and the environment inside the callback:

// Here is the outer environment
A.myf(()=>{
    // Here is the inner environment
    console.log(this); // logs 'window'
})

With arrow functions, just look to the outer environment's this to see what the inner environment's this refers to:

const outerThis = this;
A.myf(()=>{
    console.log(outerThis === this); // this will ALWAYS be true
        // if the block is created from an arrow function
})

In sloppy mode, this is the global object on the top level, so this is window inside the callback.

Upvotes: 2

Related Questions