zoukankan      html  css  js  c++  java
  • JS匿名函数自执行函数

    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>
  • 相关阅读:
    JS函数防抖与函数节流
    AJAX问题 XMLHttpRequest.status = 0是什么含义
    通过JS如何获取IP地址
    关于URL编码
    报错Unexpected token u
    css文本超出2行就隐藏并且显示省略号
    At_speed_test
    Logic Bist Arch
    Logic BIST
    DMA-330(二)
  • 原文地址:https://www.cnblogs.com/zxx193/p/3544831.html
Copyright © 2011-2022 走看看