• 自执行函数


    1、方式一:

    // 方式一
        (function fun4(){
            console.log("fun4");
        }()); // "fun4"

    2、方式二:

    // 方式二
        (function fun5(){
            console.log("fun5");
        })();// "fun4"

    3、其它方式:除了上面()小括弧可以把function关键字作为函数声明的含义转换成函数表达式外,JavaScript的&&与操作||或操作 ,逗号等操作符也有这个效果。

        true && function () { console.log("true &&") } (); // "true &&"
        false || function () { console.log("true ||") } (); // "true ||"
        0, function () { console.log("0,") } (); // "0,"
    
    // 此处要注意: &&, || 的短路效应。即: false && (表达式1)  是不会触发表达式1;
    // 同理,true || (表达式2) 不会触发表达式2
        !function () { console.log("!"); } (); //"!"
        ~function () { console.log("~"); } (); //"~"
        -function () { console.log("-"); } (); //"-"
        +function () { console.log("+"); } (); //"+"
    // 注意:采用new方式,可以不要再解释花括弧 `}` 后面加小括弧 `()` 
    new function () { console.log("new"); } //"new"
    
    // 如果需要传递参数
    new function (a) { console.log(a); } ("newwwwwwww"); //"newwwwwwww"
    //此处 要注意区分 i 和 j 不同之处。前者是函数自执行后返回值给 i ;后者是声明一个函数,函数名为 j 。
        var i = function () { console.log("output i:"); return 10; } (); // "output i:"
        var j = function () { console.log("output j:"); return 99;}
        console.log(i); // 10
        console.log(j); // ƒ () { console.log("output j:"); return 99;}
        var i2 = (function () { console.log("output i2:"); return 10; } ()); // "output i2:"
        var i3 = (function () { console.log("output i3:"); return 10; }) (); // "output i3:"
    // 以上两种都可以,但依旧建议采用第一种 i2 的方式。(个人依旧喜欢第二种i3方式)

     4、应用

    for( var i=0;i<3;i++){
        setTimeout(function(){
            console.log(i);
        }
        ,300);
    }
    // 输出结果 3,3,3
    for( var i=0;i<3;i++){
        (function(lockedIndex){
            setTimeout(function(){
                console.log(lockedIndex);
            }
            ,300);
        })(i);
    }
    // 输出 "1,2,3"
  • 相关阅读:
    替换OSD操作的优化与分析
    Centos7下Jewel版本radosgw服务启动
    如何统计Ceph的RBD真实使用容量
    Ceph中的Copyset概念和使用方法
    Proftp最简匿名访问配置
    Windows could not set the offline local information.Error code:0X80000001解决方法
    《一百岁感言》 杨绛
    取扑克牌的问题
    马云的懒人理论
    明代地图总目
  • 原文地址:https://www.cnblogs.com/jaywu/p/12789506.html
Copyright © 2020-2023  润新知