$(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 时,我得到输出:
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);
}());
这样做的目的是为了让这个函数首先在脚本标签中执行吗?
最佳答案
这有时被称为“自调用函数”,尽管该术语可能会产生误导。如前所述,这是一种创建匿名函数的方法,不将引用保存在任何地方,然后立即调用它。
该函数将永远不会再次执行。您可能会质疑它的用处,但它实际上是 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"
关于Javascript事件语法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6139905/