【问题标题】:JavaScript losing "this" context, function inside class function [duplicate]JavaScript失去“this”上下文,类函数中的函数[重复]
【发布时间】:2020-09-18 06:39:18
【问题描述】:
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 的闭包中?

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

【问题讨论】:

    标签: javascript class closures this


    【解决方案1】:

    函数c() 不是类的一部分,因此您需要使用Function.prototype.call() 将类上下文作为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();

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 关于c被直接调用:c不是在b1的范围内调用吗?
      • 问题不在于从哪里来,而在于如何......
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-15
      • 2018-08-01
      相关资源
      最近更新 更多