如何在 JavaScript 中调用自执行函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10890263/
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
How to call a self executing function in JavaScript?
提问by TK123
When I have some code I need to execute more than once I wrap it up in a function so I don't have to repeat myself. Sometimes in addition there's a need to execute this code initially on page load. Right now I do it this way:
当我有一些代码时,我需要多次执行我将它包装在一个函数中,这样我就不必重复自己了。此外,有时还需要在页面加载时最初执行此代码。现在我这样做:
function foo() {
alert('hello');
}
foo();
I would rather do it this way:
我宁愿这样做:
(function foo() {
alert('hello');
})();
Problem is, this will only execute on page load but if I try to call it subsequent times using foo()
it won't work.
问题是,这只会在页面加载时执行,但如果我尝试在以后使用foo()
它调用它,它将不起作用。
I'm guessing this is a scope issue but is there any way to get self executing functions to work upon getting called later?
我猜这是一个范围问题,但有没有办法让自执行函数在以后被调用时工作?
回答by
If your function doesn't rely on a return value, you can do this...
如果您的函数不依赖于返回值,您可以这样做...
var foo = (function bar() {
alert('hello');
return bar;
})(); // hello
foo(); // hello
This uses the local reference bar
in the named function expression to return the function to the outer foo
variable.
这使用bar
命名函数表达式中的局部引用将函数返回到外部foo
变量。
Or even if it does, you could make the return value conditional...
或者即使是这样,您也可以使返回值有条件......
var foo = (function bar() {
alert('hello');
return foo ? "some other value" : bar;
})(); // hello
alert( foo() ); // hello --- some other value
or just manually assign to the variable instead of returning...
或者只是手动分配给变量而不是返回......
var foo;
(function bar() {
alert('hello');
foo = bar;
})(); // hello
foo(); // hello
As noted by @RobG, some versions of IE will leak the identifier into the enclosing variable scope. That identifier will reference a duplicate of the function you created. To make your NFE IE-safe(r), you can nullify that reference.
正如@RobG所指出的,某些版本的 IE 会将标识符泄漏到封闭变量范围内。该标识符将引用您创建的函数的副本。为了使您的 NFE IE 安全(r),您可以取消该引用。
bar = null;
Just be aware that the identifier will still shadow an identifier with the same name up the scope chain. Nullifying won't help that, and local variables can not be deleted, so choose the NFE name wisely.
请注意,标识符仍会在作用域链上覆盖同名的标识符。无效化无济于事,并且不能删除局部变量,因此明智地选择 NFE 名称。
回答by Jord?o
To be called from outside, the function has to be visible from outside. Ideally you would have the self executing function inject it in some passed in context (in this case, this
, which references the global context):
要从外部调用,该函数必须从外部可见。理想情况下,您应该让自执行函数将它注入到一些传入的上下文中(在这种情况下,this
,它引用了全局上下文):
(function(context) {
var foo = function() {
alert('hello');
};
foo();
context.foo = foo;
})(this);
...
foo();
? More interesting patterns can be found here.
? 更多有趣的模式可以在这里找到。
回答by nnnnnn
If foo()
is intended to be a global function, i.e., a property of window
, you can do this:
如果foo()
打算成为一个全局函数,即 的属性window
,你可以这样做:
(window.foo = function() {
alert('hello');
})();
// at some later time
foo();
The expression in the first set of parentheses does the assignment to create foo
, but also evaluates to be the function so you can invoke it immediately with ()
on the end.
第一组括号中的表达式执行对 create 的赋值foo
,但也计算为函数,因此您可以()
在末尾立即调用它。
This pattern works even if the function is supposed to return a value.
即使函数应该返回一个值,这种模式也能工作。
回答by zhenguoli
The second function foo
is a function definition expression.
第二个函数foo
是函数定义表达式。
In a function definition expression, you can only call the function with the name within the function itself according to "Javascript the definitive guide":
在函数定义表达式中,您只能根据“Javascript 权威指南”在函数本身内调用具有名称的函数:
For function definition expressions, the name is optional: if present, the name refers to the function object only within the body of the function itself.
对于函数定义表达式,名称是可选的:如果存在,则名称仅在函数本身的主体内引用函数对象。
It can be used in a recursion function definition expression.
它可以用在递归函数定义表达式中。
For example:
例如:
var f = function factorial(n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n-1);
}