js匿名函數

  (function($){})(jquery) == (function($){})(jQuery)

  实际上是匿名函数

  用于存放开发插件的代码 

  作用(非常有用):

  这种写法的最大好处是形成闭包。在(function($) {…})(jQuery)在内部定义的函数和变量只能在此范围内有效。

  形成是否函数函数、私有变量的概念。比如:

  1. var i=3;  
  2. function init(){  
  3.     alert("外层init:"+i);  
  4. }  
  5. (function($) {  
  6.     var i=2;  
  7.     function init(){  
  8.         alert("内层init:"+i);  
  9.     }  
  10.   
  11.     init();  
  12. })(jQuery);  
  13. init();  

    执行结果:

    内层init:2

    外层init:3

   以下是一個實驗的例子

   <script src="js/jquery-1.7.1.min.js"></script>
   <script type="text/javascript">

        //(function ($) {
        //    alert(1);
        //    $.a = function (i)
        //    {
        //        alert(i.name);
        //        this.shows = function (j)
        //        {
        //            alert(j);
        //            alert(3);
        //            abc();
        //            def();
        //        }
        //        abc = function ()
        //        {
        //            alert(4);
        //        }
        //        def = function ()
        //        {
        //            i.callBack(666666);
        //        }
        //    }
        //})($);
        //var i = new $.a({
        //    name:"sdy",
        //    callBack: function (no)
        //    {
        //        alert(no);
        //        alert(1234);
        //    }
        //});
        //i.shows(123);


        function MM($) {
            alert(2);
            $.a = function (i) {
                alert(i.name);
                this.shows = function (j) {//this為必須寫的
                    alert(j);
                    alert(1);
                    cc();
                }
                aa = function () {
                    alert("aa");
                }
                bb = function () {
                    alert("bb");
                }
                cc = function ()
                {
                    i.callBank("回調函數");//回調函數 callBack 寫錯也沒事 哈哈哈哈
                }
            }
        };
        MM(jQuery);
        var abc = new $.a({
            name: "sdy", callBank: function (no)
            {
                alert(no);
            }
        });
        abc.shows(1);
        //(function ($) {
        //    alert(1);
        //    alert($);
        //})(jQuery);

        //function MM($) {
        //    alert(2);
        //}
        //MM(jQuery)
            
        //    (function(str){alert(str)})("aaa");
        ////相当于:
        //function OutPutFun(str) { alert(str); };
        //OutPutFun("output");

posted @ 2016-01-20 17:34  好好學習  阅读(168)  评论(0编辑  收藏  举报