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.
A function which is defined inside another function is known as inner function or nested functio n. Nested functions are able to access variables of the enclosing scope. Inner functions are used so that they can be protected from everything happening outside the function.
In JavaScript, a nested function is a function that is defined inside or within another function. The procedure for creating a nested function is the same as we follow for the normal function, but to create a nested function, we have to define the new or the child function inside the parent function.
The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With