jquery function inside a function
Is it possible to have a function within another function开发者_如何学Python like so?
function foo() {
// do something
function bar() {
// do something
}
bar();
}
foo();
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.
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.
精彩评论