Calling a Function defined inside another function in Javascript

前端 未结 6 533
醉酒成梦
醉酒成梦 2020-12-02 13:12

I am calling a function on button click like this:

​

function outer() { 
    alert(\"hi\"         


        
相关标签:
6条回答
  • 2020-12-02 13:39

    You are not calling the function inner, just defining it.

    function outer() { 
        function inner() {
            alert("hi");
        }
    
        inner(); //Call the inner function
    
    }
    
    0 讨论(0)
  • 2020-12-02 13:44

    You can also try this.Here you are returning the function "inside" and invoking with the second set of parenthesis.

    function outer() {
      return (function inside(){
        console.log("Inside inside function");
      });
    }
    outer()();
    

    Or

    function outer2() {
        let inside = function inside(){
          console.log("Inside inside");
        };
        return inside;
      }
    outer2()();
    
    0 讨论(0)
  • 2020-12-02 13:46

    If you want to call the "inner" function with the "outer" function, you can do this:

    function outer() { 
         function inner() {
              alert("hi");
         }
         return { inner };
    }
    

    And on "onclick" event you call the function like this:

    <input type="button" onclick="outer().inner();" value="ACTION">​
    
    0 讨论(0)
  • You could make it into a module and expose your inner function by returning it in an Object.

    function outer() { 
        function inner() {
            console.log("hi");
        }
        return {
            inner: inner
        };
    }
    var foo = outer();
    foo.inner();
    
    0 讨论(0)
  • 2020-12-02 13:53

    The scoping is correct as you've noted. However, you are not calling the inner function anywhere.

    You can do either:

    function outer() { 
    
        // when you define it this way, the inner function will be accessible only from 
        // inside the outer function
    
        function inner() {
            alert("hi");
        }
        inner(); // call it
    }
    

    Or

    function outer() { 
        this.inner = function() {
            alert("hi");
        }
    }
    
    <input type="button" onclick="(new outer()).inner();" value="ACTION">​
    
    0 讨论(0)
  • 2020-12-02 14:00

    you can also just use return:

       function outer() { 
        function inner() {
            alert("hi");
        }
    return inner();
    
    }
    outer();
    
    0 讨论(0)
提交回复
热议问题