2011-05-26 18 views
2
$(document).ready(function(){ 
    console.log('a'); 
}); 

window.fbAsyncInit = function() { 
    FB.init({appId: '{/literal}{$fbAppId}{literal}', 
      status: true, 
      cookie: true, 
      xfbml: true}); 

    FB.Event.subscribe('edge.create', function(response) { 
     // Do something, e.g. track the click on the "Like" button here 
     if(!liked) 
     { 
      {/literal}$.get('http://{$rooturl}/promotions/likecheck.php?CID={$CID}&ctype={$campaignTable}');{literal} 
      liked=true; 
     } 
    }); 
}; 
(function() { 
    console.log('b'); 
    var e = document.createElement('script'); 
    e.type = 'text/javascript'; 
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; 
    e.async = true; 
    document.getElementById('fb-root').appendChild(e); 
}()); 

我注意到,当我运行这个JavaScript在我的控制台我得到的输出:的Javascript事件语法问题

b 
a 

我想知道这是什么意思包裹在括号中的函数在这里的JavaScript:

(function() { 
    console.log('b'); 
    var e = document.createElement('script'); 
    e.type = 'text/javascript'; 
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; 
    e.async = true; 
    document.getElementById('fb-root').appendChild(e); 
}()); 

这样做的目的是使这个功能第一次执行脚本标记?

回答

1

这有时被称为“自我调用功能”,尽管该术语可能会引起误解。如前所述,这是创建匿名函数的一种方式,不要将引用保存到任何地方,然后立即调用它。

该函数将永远不会再次执行。您可能会质疑这一点的用处,但它实际上是一个good practice来指示这是实际的程序代码,与函数或其他对象定义分开。

但是,您仍然必须使用var关键字ensure you don't pollute the global namespace

为例:

var outside = "Hello Outside"; 
(function() 
{ 
    alert(outside); // Works as expected. 

    // Define some variable and see what happens. 
    globalVar = "Hello World, redux"; 
    var localVar = "Hello World"; 
}()); 

alert(globalVar); 
alert(localVar); // Get an error: "localVar is not defined" 
1

这样做的目的仅仅是创建一个私有的词法范围,以便由该范围代码声明的变量不会污染全局名称空间。它确实而不是强制代码执行“第一”。

因此,例如,变量“e”将在函数执行后消失,并且不会有任何“e”浮动以扰乱其他任何代码。

1

这是一种创建函数(使用自己的闭包和变量)并立即调用的方法,但不会污染全局名称空间。