Javascript 函数内的jquery函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6783434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery function inside a function
提问by daryl
Is it possible to have a function within another function like so?
是否有可能在另一个函数中具有这样的函数?
function foo() {
// do something
function bar() {
// do something
}
bar();
}
foo();
回答by Mrchief
Yes you can have it like that. bar
won't be visible to anyone outside foo
.
是的,你可以这样。bar
外面的任何人都看不到foo
。
And you can call bar
inside foo
as:
您可以bar
在内部调用foo
:
function foo() {
// do something
function bar() {
// do something
}
bar();
}
回答by u283863
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,
或者你希望函数“bar”是通用的,
function foo(){
window.bar=function(){
//something here
}
}
Hop this helps you.
跳这对你有帮助。
回答by GarlicFries
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.
这在 Javascript 中称为嵌套函数。内部函数对于外部函数是私有的,并且也形成了一个闭包。可在此处获得更多详细信息。
Be particularly careful of variable name collisions, however. A variable in the outer function is visible to the inner function, but not vice versa.
但是,要特别小心变量名冲突。外部函数中的变量对内部函数可见,反之则不然。