JavaScript 封闭函数

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>封闭函数</title>
    <script>
        
        /*
        function myAlert(){
            alert('Hello World')
        }
        myAlert();
        */
        // 第一中写法:
        //使用小括号包裹函数
        (function(){
            iNum01 = 'Hello World';
            alert(iNum01);
        })();

        // 第二种写法:
        // 函数前加 !
        !function(){
            iNum01 = 'hello wooooooorld';
            alert(iNum01)
        }();

        // 第三种写法:
        // 函数前加 ~
        ~function(){
            iNum01 = 'hello wooooooorld aaaaaaagain';
            alert(iNum01)
        }();

        /*

        封闭函数的好处:
            封闭函数可以创造一个独立的空间,里面定义的变量和函数不会影响外面的通同名变量和函数 , 可避免命名冲突 . 在引用js文件的时候,避免冲突.
            类似于闭包 , 私有方法.

            迭代版本时候更多使用封闭函数,一边对现有功能产生不必要影响

        */

    </script>

</head>
<body>
    
</body>
</html>

 

posted @ 2019-08-13 17:41  Jrri  阅读(442)  评论(0编辑  收藏  举报