JS匿名函数自执行函数

时间:2023-03-08 21:38:22

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>