JavaScript 丢失 "this" 上下文,class 函数内的函数

JavaScript losing "this" context, function inside class function

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

在这种情况下,当调用 a.b1() 时,在函数 b1 的范围内,this 上下文绑定到 a。但是当在函数 b1 中执行函数 c 时,为什么 this 上下文丢失了? this 假设在函数的闭包中 c ?

我知道如何让它工作(箭头功能)。只是想知道为什么。

函数 c() 不是 class 的一部分,因此您需要使用 Function.prototype.call() 将 class 上下文作为 this 传递或使用箭头函数来声明它

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();

this 不是从闭包中获取的,除非您使用箭头函数,而是通过调用函数的方式接收到的。

由于直接调用了c,所以这里指的是undefined

您可以将 c 声明为箭头函数以从封闭范围中获取它

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();