Is it possible to have a function within another function like so?
function foo() {
// do something
function bar() {
// do something
}
bar();
}
foo();
-
1@ gion_13: strictly speaking having a function within a function is not a "closure". The aspect that the function will preserve any variables in its scope even if they are not part of the function body itself (i.e. non-local variables) makes it a "closure".FK82– FK822011年07月21日 22:40:40 +00:00Commented Jul 21, 2011 at 22:40
3 Answers 3
Yes you can have it like that. bar won't be visible to anyone outside foo.
And you can call bar inside foo as:
function foo() {
// do something
function bar() {
// do something
}
bar();
}
Yes, you can.
Or you can do this,
function foo(){
(function(){
//do something here
})()
}
Or this,
function foo(){
var bar=function(){
//do something here
}
}
Or you want the function "bar" to be universal,
function foo(){
window.bar=function(){
//something here
}
}
Hop this helps you.
Comments
That's called a nested function in Javascript. The inner function is private to the outer function, and also forms a closure. More details are available here.
Be particularly careful of variable name collisions, however. A variable in the outer function is visible to the inner function, but not vice versa.