Jquery function inside function

Is it possible to have a function inside another function?

function foo() { // do something function bar() { // do something } bar(); } foo(); 
+7
source share
3 answers

Yes you can do it. bar will not be displayed to anyone outside of foo .

And you can call bar inside foo like:

 function foo() { // do something function bar() { // do something } bar(); } 
+14
source

Yes, you can.
Or you can do it,

 function foo(){ (function(){ //do something here })() } 

Or that,

 function foo(){ var bar=function(){ //do something here } } 

Or do you want the bar function to be universal,

 function foo(){ window.bar=function(){ //something here } } 

This will help you.

+4
source

This is called a nested function in Javascript. The inner function is private to the outer function, and also forms a closure. More information is available here .

Be especially careful when colliding with variable names. A variable in an external function is visible to an internal function, but not vice versa.

+3
source

All Articles