JS作用域與閉包--例項

qingyezhu發表於2014-08-27
    
    <script>
        "use strict"
        //函式作用域
        function func(){
            var arr = [1,3,5,7,9];
            var sum = 0;
            for(var i = 0,len = arr.length;i < len;i ++){
                sum += arr[i];
            }
            console.log("%d\t\n%d",i,sum);
        }
        func();
        //5
        //25
        
        //閉包特性
        var outter = [];
        function clouseTest(){
            var arr = ["one","two","three","four"];
            for(var i = 0, len = arr.length;i < len;i ++){
                var x = {};
                x.no = i;
                x.text = arr[i];
                x.invoke = function(){
                    console.log("%d\t\n%o\t\n%d\t\n",i,this,this.no);
                };
                outter.push(x);
            }
        }
        
        clouseTest();
        for(var i = outter.length - 1;i >= 0;i --){
            outter[i].invoke();
        }
        //4
        //Object { no=3, text="four", invoke=function()}
        //3

        //4
        //Object { no=2, text="three", invoke=function()}
        //2

        //4
        //Object { no=1, text="two", invoke=function()}
        //1
        
        //4
        //Object { no=0, text="one", invoke=function()}
        //0
        
        //關於i輸出的都是4的解釋:因為,在每次迭代的時候這樣的語句x.invoke=function(){console("%d",i);}並沒有
        //被執行,只是構建了一個函式體為“console.log("%d",i);”的函式物件,如此而已。而當i = 4時,迭代停止,外部函式返回
        //當再去呼叫outter[i].invoke()時,i的值依舊為4,因此outter陣列中的每一個元素的invoke都返回i的值為4.
        
        
        //引用
        var obj = {};//空物件
        var ref = obj;//引用
        obj.name = "objectA";//
        console.log(ref.name);//ref跟著剛新增的name屬性
        obj =  ["one","two","three","four"];//obj指向了另一個物件(陣列物件)
        console.log(ref.name);//ref還指向原來的物件
        console.log(obj.length);//4
        console.log(ref.length);//undefined
        
        //objectA
        //objectA
        //4
        //undefined
        
        //作用域問題:內部函式可以訪問外部函式中的變數,(在非嚴格模式下,當此時內部函式中的this卻是指向window)
        var name = "window";
        function wrapper(){
            var name = "wrapper";
            
            function inner(){
                console.log('%s',name);//wrapper
                console.log('%o',this);//在嚴格模式( use strict)下是 undefined,否則指向 window
                //console.log('%s',this.name);//在嚴格模式(use strict)下,是undefined error,否則是 'window'
            }
            inner();
        }
        wrapper();
         
                
        function wrapper2(){
            var name = "local";
            return function(){
                console.log('%s',name);//local
                console.log('%o',this);//在嚴格模式( use strict)下是 undefined,否則指向 window
                //console.log('%s',this.name);//在嚴格模式(use strict)下,是undefined error,否則是 'window'
            };
        }
        
        wrapper2()();
        
    </script>

 

相關文章