Calling a Function defined inside another function in JavaScript | Example

How to call a child function inside a function from another function in Javascript?

function Hello()
{
  function HelloAgain(){
  }
}

function MyFunction(){
...
}

Want to call the function HelloAgain() from MyFunction().

Answer: You can’t. The scope of HelloAgain is limited to the Hello function. This is the only way to make private scope in javascript.

But you can use the this keyword to deal with the matter.

<!DOCTYPE html>
<html>
<head>
    <body>

        <script type="text/javascript">
            function Hello () {

                console.log("Hello");

                this.helloAgain = function helloAgain () {
                    console.log("Hello Again");
                }
            }

            var hello = new Hello();

            function MyFunction () {
              hello.helloAgain();
          }
          //Test
          MyFunction();


      </script>
  </body>
  </html>

Output:

Calling a Function defined inside another function in JavaScript

Want a call a inner function on button click:

function outer() { 

<input type="button" onclick="outer();" value="ACTION">​
    function inner() {
        alert("Hello");
    }
}

Let’s see solution and HTML example codes for it:-

Solution 1: Call inner function in Outer function

Define function this way, the inner function will be accessible only from inside the outer function.

<!DOCTYPE html>
<html>
<head>
    <body>

        <input type="button" onclick="outer();" value="ACTION">​

        <script type="text/javascript">
            function outer() { 
                function inner() {
                    alert("Hello");
                }
            inner(); // call it
        }
</script>
</body>
</html>

Solution 2: Using this keyword

<!DOCTYPE html>
<html>
<head>
    <body>

     <input type="button" onclick="(new outer()).inner();" value="ACTION">​

     <script type="text/javascript">
        function outer() { 
            this.inner = function() {
                alert("Hello");
            }
        }
        
    </script>
</body>
</html>

Output:

Calling a Function defined inside another function in JavaScript

Do comment if you have any doubts and suggestion on this topic.

Note: All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.