简体   繁体   中英

how to call outer class function from inner function in Javascript?

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

I am trying to split the code into functions, for readability. But this doesnt work, how can I call an outer class function from an inner function?

It's a matter of scope. When you get to functionWeCall() , this starts referring to that very function instead of to the class, thus outFunction() doesn't exist on this . A typical workaround might look like this:

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

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

... but I'd rather advice reworking the whole thing so that you don't have nested functions like that.

Edit: as suggested by @Aluan Haddad, here's the same thing, but with an arrow function:

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

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

... and if you want the inner function to still be callable, assign it to a variable:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM