“JavaScript丢失”;这";上下文,类函数中的函数

“JavaScript丢失”;这";上下文,类函数中的函数,javascript,class,closures,this,Javascript,Class,Closures,This,在这种情况下,当调用a.b1()时,在函数b1的范围内,this上下文绑定到a。但是,当在函数b1内部执行函数c时,为什么会丢失此上下文这个假设在函数c的闭包中 我知道如何使它工作(箭头功能)。只是想知道为什么。函数c()不是类的一部分,因此您需要使用在类上下文中作为this传递,或者使用箭头函数声明它 b类{ 构造函数(){ this.name='bar' } b1(){ console.log('here:',this.name); 函数c(){ console.log('inside

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

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

函数
c()
不是类的一部分,因此您需要使用在类上下文中作为
this
传递,或者使用箭头函数声明它

b类{
构造函数(){
this.name='bar'
} 
b1(){
console.log('here:',this.name);
函数c(){
console.log('inside c:',this.name)
} 
c、 叫(这个);
}
}
设a=新b;

a、 b1()
除非使用箭头函数,否则此
不会从闭包中获取,而是通过调用函数的方式接收

由于直接调用了
c
,因此这里指的是
undefined

您可以将c声明为一个arrow函数,以从封闭范围中获取它

b类{
构造函数(){
this.name='bar'
} 
b1(){
console.log('here:',this.name);
常数c=()=>{
console.log('inside c:',this.name)
} 
c();
}
}
设a=新b;

a、 b1()
关于直接调用
c
:是否在
b1
的范围内调用
c
?问题不是从何处调用,而是如何调用。。如果你看a,a.b1将导致b1将其作为
a
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