-2

I'm fairly new to typescript coding but I've been managing fine so far with prior knowledge of coding, but I've stumbled a problem that I wasn't able to find a comprehensible answer... I think.

myMethod1(){
  function mySubMethod(){
  //Call myMethod2 here.
  }
}
myMethod2(){
//do something
}

Is this possible? Sorry about this and thanks.

1 Answers1

0

Yes, it's entirely possible, because mySubMethod is declared in a scope nested inside the scope that myMethod2 is declared in. Inner scopes can access outer scope bindings, just not the other way around.

You do need to declare the functions correctly, though:

function myMethod1(){
    function mySubMethod(){
        myMethod2();
    }
    mySubMethod();
}
function myMethod2(){
    console.log("myMethod2 ran");
}
myMethod1();

Side note: As shown, what you have there are functions, not methods. Methods are associated with an object.


In a comment you've clarified:

myMethod1 and myMethod2 are methods and mySubMethod is a function and not a method

So that sounds like this:

class Example {
    myMethod1(){
        function mySubMethod(){
            this.myMethod2();
        }
        mySubMethod.call(this);
        
        // Easier with an arrow function:
        const mySubFunction = () => {
            this.myMethod2();
        };
        mySubFunction();
    }
    myMethod2(){
        console.log("myMethod2 ran");
    }
}
const e = new Example();
e.myMethod1();

Mostly it's about managing this in this particular case. More:

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639