为什么/何时/何时应该这样做? (将js代码包含在函数内,然后执行它)

时间:2010-08-31 18:51:00

标签: javascript design-patterns

  

可能重复:
  JavaScript scope and closure

这是为了什么?

(function(){
     //The code to be executed
})(); 

另外,这与封闭有什么关系吗?

4 个答案:

答案 0 :(得分:5)

我最近经常看到它。我在猜测:

无需命名该功能。这意味着它不可重复使用。 这为您提供了使用var声明变量的局部范围(否则,您可以将它们添加到全局)。

答案 1 :(得分:0)

这是Javascript中的closureanonymous function - 关键概念。 Javascript没有'true'私有属性或字段 - 但是使用闭包你基本上可以创建等价物。它们是组织JS的一种非常重要的手段。

此示例中的一个关键点是代码最后的(); - 添加这些括号使Javascript立即执行代码 - 有效地初始化其中包含的内容

http://www.jibbering.com/faq/notes/closures/


为了帮助澄清(我不是JS专家) - 这个构造,即使不是纯粹的闭包,也常常与闭包一起出现。例如,以下代码段(从我上面的链接复制)使用此语法来定义内部隐藏方法:

function callLater(paramA, paramB, paramC){
    /* Return a reference to an anonymous inner function created
       with a function expression:-
    */
    return (function(){
        /* This inner function is to be executed with - setTimeout
           - and when it is executed it can read, and act upon, the
           parameters passed to the outer function:-
        */
        paramA[paramB] = paramC;
    });
}

...

/* Call the function that will return a reference to the inner function
   object created in its execution context. Passing the parameters that
   the inner function will use when it is eventually executed as
   arguments to the outer function. The returned reference to the inner
   function object is assigned to a local variable:-
*/
var functRef = callLater(elStyle, "display", "none");
/* Call the setTimeout function, passing the reference to the inner
   function assigned to the - functRef - variable as the first argument:-
*/
hideMenu=setTimeout(functRef, 500);

虽然:这个示例在内部函数定义之后不会立即执行(它缺少();)。因此,在这种情况下,封闭函数将在稍后的时间点进行评估 - 那些()在函数式语言中有很大的不同。

答案 2 :(得分:0)

它用于运行全局范围的代码OUT。 有了这个,您正在使用功能范围。在这种情况下,匿名函数的范围。

例如,当您不想创建全局变量时,这非常有用。

请参阅:

var b = 2;
(function(){
    var a=1;
    alert("a:" + a); // alerts 1
    alert("b:" + b); // alerts 2
})();
alert("OUT b:" + b); // alerts 2
alert("OUT a:" + a); // undefined

jsfiddle


修改

语法()()是另一种调用函数的方法。 见

alert(1); // alerts 1
(alert)(2); // alerts 2

jsfiddle

答案 3 :(得分:0)

它是一种定义函数并立即调用它的方法。多数民众赞成在最后();确实