1

自执行函数

下面三个自执行函数是一样的

        //1.
        function test(i){
            console.log(i)
        }
        test("aa")

        //2.
        (function(i){
            console.log(i)
        })('aa')

        // 3.
        var aa = "aa";
        (function(i){
            console.log(i)
        })(aa)
        var a = [1, 2, 3, 4]; {
            var a = [1, 2, 3, 4, 5];
            (function(i) {
                var a = [1, 2, 3, 4, 5, 6];
                for (var i = 0; i < a.length; i++) {
                    console.log(i)  //0,1,2,3,4,5
                }
            })(a)
        }

this

        var num =1;
        var obj = {
            num:2,
            fn:(function(num){
                this.num*=2;
                num+=2;
                return function(){
                    this.num*=3;
                    num++;
                    console.log(num)
                }
            })(num)  //window下的num
        }
        var fn = obj.fn;
        fn();  //4
        obj.fn()  //5
        console.log(num,obj.num); //6,6

fn()

console.log(fn)
console.log(obj.fn())

clipboard.png

拆分

        var num =1;
        var obj = {
            num:2,
            fn:(function(num){
                this.num*=2;
                num+=2;
                console.log(this)  //window
                return function(){
                    this.num*=3;
                    num++;
                    console.log(this)  //window
                    console.log(num)   //4
                    console.log(this.num)  //6
                }
            })(num)  //window下的num
        }
        var fn = obj.fn;
        fn();  
        console.log(num,obj.num); //6,2
        var num =1;
        var obj = {
            num:2,
            fn:(function(num){
                this.num*=2;
                num+=2;
                console.log(this)  //window
                return function(){
                    this.num*=3;
                    num++;
                    console.log(this)  //obj
                    console.log(num)  //4
                    console.log(this.num)   //6
                }
            })(num)  //window下的num
        }
        var fn = obj.fn; 
        obj.fn()  
        console.log(num,obj.num); //2,6

渣渣辉
1.3k 声望147 粉丝