美文网首页
javascript封闭函数

javascript封闭函数

作者: Oo晨晨oO | 来源:发表于2018-01-22 22:33 被阅读29次

    封闭函数是将一些执行语句包含在一个区域的一种写法

    语法

    1. 将一些语句用(function(){...})() 包起来
      比如
    ;(function (index){
                aBtn[index].onclick=function(){
                    for(var i=0;i<aBtn.length;i++){
                        aBtn[i].className='';
                        aDiv[i].style.display='none';
                    }
                    this.className='on';
                    aDiv[index].style.display='block';
                };
            })(i);
    

    这种写法要在前面加一个分号; 以防止之后代码压缩执行错乱

    1. 其他写法
    ~(function(){ 
    alert('water'); 
    })();
       
    void function(){ 
    alert('water'); 
    }();//据说效率最高
       
    +function(){ 
    alert('water'); 
    }(); 
       
    -function(){ 
    alert('water'); 
    }(); 
       
    ~function(){ 
    alert('water'); 
    }(); 
       
    !function(){ 
    alert('water'); 
    }(); 
      
    (function(){ 
    alert('water'); 
    }());//有点强制执行的味道
    

    这样写的好处

    1. 可以在定义函数的同时又可以执行它,省去命名的步骤;
    2. 封闭空间里定义的变量是这个空间里的局部变量。

    相关文章

      网友评论

          本文标题:javascript封闭函数

          本文链接:https://www.haomeiwen.com/subject/ienraxtx.html