Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a Function defined inside another function in Javascript

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.

like image 527
Mike Avatar asked Nov 04 '12 12:11

Mike


People also ask

Can you define function inside another 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.

What is nested function in JavaScript?

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.

How do you call invoke this function inside a JavaScript code?

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.


1 Answers

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(); 
like image 166
Matt Holmes Avatar answered Sep 19 '22 15:09

Matt Holmes