关于匿名函数自执行

赋值式(将匿名函数赋给变量)表达式定义法    声明式
            var fn_01 = function(){
                alert("匿名函数");
            }
            fn_01(); //如果想调用fn_01函数,写该函数的名称,然后写小括号就可以了
            
 将一个匿名函数用小括号括起来,后面加一个小括号,表示匿名函数的自执行(可以防止变量污染)
            (function(){
                alert("匿名函数");
            })();
            
带参数的匿名函数自执行
            (function(a,b){   //形参:定义函数时接收数据的参数
                alert(a + b);
            })(1,2);
            
有返回值的匿名函数的自执行
            var res = (function(a,b){
                return a > b ? a : b;
            })(3,4);
            alert(res);
            
将一个匿名函数赋值给一个表达式,在该匿名函数后加一个小括号,表示匿名函数自执行
            var fn_02 = function(){
                alert("匿名函数");
            }();

            alert( fn_02 );
            var fn_03 = function(){
                return 23;
            }();
            alert( fn_03 );     //fn_02接收了匿名函数的返回值
            
拓展小知识:
            ~ function(){console.log("hello world1");}();
            ! function(){console.log("hello world2");}();
            + function(){console.log("hello world3");}();
            - function(){console.log("hello world4");}();


            delete function(){console.log("hello world5");}();
            void function(){console.log("hello world6");}();
            
            var result = 1 + function(){return 1}();
            alert(result);     //2
            
            (function(){console.log("hello world7");})();
            (function(){console.log("hello world8");}());
           

猜你喜欢

转载自www.cnblogs.com/lisaShare/p/9000017.html
今日推荐