您的位置:首页 > Web前端 > JavaScript

JS匿名函数自执行函数

2014-02-11 17:43 183 查看
JS匿名函数自执行函数:(function(){})();
(function(){}) 这是一个函数,函数后面接(),则是调用函数
比如(function(arg){console.log(arg);})(4); 则输出4

好处:放在里面,不会污染外面的变量,也保护了自己,外面调用不了里面的函数和变量。
在js中写大量代码,可以防止变量冲突和错误调用。

插件常用的是
( function ($ ) {
// 插件代码
} ) (jQuery ) ;

这样的好处是可以在函数内自由使用$,不用担心跟别的库冲突。 http://jack.wilead.com/jquery-plugin-develop/
示例js文件代码:

(function()
{
var defaultRightBar =
{
removeFloathyd: function()
{
var divfloathyd = jQuery("#div_floathyd");
if (divfloathyd.data("random") == random && divfloathyd.data("focus") == "false")
{
divfloathyd.remove();
}
},
bindChildAccountCount: function() {
$.get(
"/Ajax/Index.ashx",
{
ajaxMethod: "getChildAccountCount",
random: Math.random()
},
function(data) {
$("#divZMAcount").html(data);
}
)
}
};
window.defaultRightBar = defaultRightBar;
})();


前端页面调用:

<script type="text/javascript" src="/js/shili.js"></script>
<script type="text/javascript">
void function()
{
defaultRightBar.bindChildAccountCount();
} ();
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: