如何在Javascript中从内部函数调用外部类函数?

时间:2020-09-04 11:55:44

标签: javascript typescript class oop

class Outer{
    private outFunction(){
       console.log("Okay!");
    }
    public functionWeCall(){
         function innerFunction(){
             this.outFunction();    //That doesn't work
         }
    }
}

为了便于阅读,我正在尝试将代码拆分为多个函数。但这不起作用,如何从内部函数调用外部类函数?

1 个答案:

答案 0 :(得分:5)

这是范围的问题。当您进入functionWeCall()时,this开始引用该函数而不是类,因此outFunction()this上不存在。一个典型的解决方法可能是这样的:

class Outer {
  private outFunction() {
    console.log("Okay!");
  }

  public functionWeCall() {
    let _this = this;
    
    function innerFunction() {
        _this.outFunction();
    }
  }
}

...但是我宁愿建议对整个过程进行重新设计,以免您没有像这样的嵌套函数。

编辑:如@Aluan Haddad所建议,这是同一件事,但具有箭头功能:

class Outer {
  private outFunction() {
    console.log("Okay!");
  }

  public functionWeCall() {
    () => {
      this.outFunction();
    }
  }
}

...,如果您希望内部函数仍然可调用,请将其分配给变量:

class Outer {
  private outFunction() {
    console.log("Okay!");
  }

  public functionWeCall() {
    let innerFunction = () => {
      this.outFunction();
    }
    
    innerFunction(); // this could be anywhere in the scope of functionWeCall()
  }
}