1
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?

3
  • 1
    Probably the reason is the outFunction is private. Commented Sep 4, 2020 at 12:02
  • 2
    @Chaz a local function defined inside a member function is part of the class and therefore can access private members Commented Sep 4, 2020 at 12:11
  • 1
    Privacy is also irrelevant. You simply have the wrong this. Commented Sep 4, 2020 at 12:46

1 Answer 1

6

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()
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I don't think of it as a workaround or something that should necessarily be refactored. Sometimes a nested function is exactly what you need. If you are going to use this, you commonly need to create functions that close over this, i.e. to pass to some other function, and such functions are by definition nested.
Thanks, adding 'this' inside the function would probably work as well but I think this case is problem, I can't divide my functions without declaring a temporary variable '_this'.
@Sahin, arrow functions, =>, were added to JavaScript because this is a common annoyance. Arrow functions don't have their own this so you can use it like you would any other variable inside one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.