如何在JavaScript中调用自执行函数? [英] How to call a self executing function in JavaScript?

查看:1330
本文介绍了如何在JavaScript中调用自执行函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有一些代码时,我需要多次执行,我将它包装在一个函数中,所以我不必重复自己。有时需要在页面加载时最初执行此代码。现在我这样做:

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();

我宁愿这样做:

(function foo() {
   alert('hello');
})();

问题是,这只会在页面加载时执行,但如果我尝试使用<后续调用它code> foo()它不起作用。

Problem is, this will only execute on page load but if I try to call it subsequent times using foo() it won't work.

我猜这是一个范围问题但有什么办法让自执行函数在以后调用时工作?

I'm guessing this is a scope issue but is there any way to get self executing functions to work upon getting called later?

推荐答案

如果你的函数不依赖于返回值,你可以这样做......

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

这使用本地参考 bar 在命名函数表达式中将函数返回到外部 foo 变量。

This uses the local reference bar in the named function expression to return the function to the outer foo variable.

或者即使它确实如此,你也可以使返回值有条件...

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






@RobG ,某些版本的IE会将标识符泄漏到封闭变量范围内。该标识符将引用您创建的函数的副本。要使您的NFE IE安全(r),您可以使该引用无效。


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.

bar = null;

请注意,标识符仍然会影响范围链上具有相同名称的标识符。 Nullifying对此无效,并且无法删除局部变量,因此请明智地选择NFE名称。

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.

这篇关于如何在JavaScript中调用自执行函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆