-2
class b { 
  constructor(){
    this.name = 'bar'
  } 
  b1(){
    console.log('here: ', this.name); 
    function c() {
      console.log('inside c: ', this.name)
    } 
    c();
  }
}

let a = new b; 
a.b1();

//output:
// here:  bar
// inside c:  undefined

In this case, when calling a.b1(), in the scope of function b1, the this context is bind to a. But when executing function c inside function b1, why the this context is lost? this suppose in the closure of function c ?

I know how to make it work (arrow function). Just wondering why.

2 Answers2

0

Function c() is not part of the class so you would need to use Function.prototype.call() to pass in the class context as this or use arrow functions to declare it

class b { 
  constructor(){
    this.name = 'bar'
  } 
  b1(){
    console.log('here: ', this.name); 
    function c() {
      console.log('inside c: ', this.name)
    } 
    c.call(this);
  }
}

let a = new b; 
a.b1();
charlietfl
  • 164,229
  • 13
  • 110
  • 143
-1

this isn't obtained from closure unless you use an arrow function, instead it as received by how the function is called.

Since c is called directly, this here refers to undefined.

You can declare c to be an arrow function to get this from the enclosing scope

class b { 
      constructor(){
        this.name = 'bar'
      } 
      b1(){
        console.log('here: ', this.name); 
        const c = ()  => {
          console.log('inside c: ', this.name)
        } 
        c();
      }
    }
    
    let a = new b; 
    a.b1();
Shubham Khatri
  • 211,155
  • 45
  • 305
  • 318