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

    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"
  • 相关阅读:
    在独立的文件里定义WPF资源
    Irrlicht 3D Engine 笔记系列 之 教程6- 2D Graphics
    Java实现二叉树的创建、递归/非递归遍历
    NDK在windows下的开发环境搭建及开发过程
    硬件路由转发原理浅析
    ubuntu下vim中内容拷贝到浏览器
    python调用Java代码,完毕JBPM工作流application
    C++组合通信
    linux杂谈(十八):DNSserver的配置(一)
    Codeforces 550D. Regular Bridge 构造
  • 原文地址:https://www.cnblogs.com/jaywu/p/12789506.html
Copyright © 2011-2022 走看看