Calling a Function defined inside another function

2020-02-08 00:52发布

I am calling a function on button click like this:

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

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

It works fine and I get an alert:

Now when I do like this:

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

Why don't I get an alert?

Though inner function has a scope available in outer function.

4条回答
对你真心纯属浪费
2楼-- · 2020-02-08 01:26

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()();
查看更多
手持菜刀,她持情操
3楼-- · 2020-02-08 01:31

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">​
查看更多
The star\"
4楼-- · 2020-02-08 01:42

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();
查看更多
Lonely孤独者°
5楼-- · 2020-02-08 01:46

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

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

    inner(); //Call the inner function

}
查看更多
登录 后发表回答