this

作者: 卡农me | 来源:发表于2019-01-08 00:05 被阅读5次

    1.简单的讲,this的指向是由所在函数的调用方式决定的

    function aa(name){
    this.b = name;
    }
    aa('tc');
    window.b  // tc
    

    而此处的直接调用方式,this指向window对象。

    函数独立调用时,this默认绑定到window

    function foo(){
        console.log(this === window);
    }
    foo(); //true
    

    被嵌套的函数独立调用时,this默认绑定到window

    //虽然test()函数被嵌套在obj.foo()函数中,但test()函数是独立调用,而不是方法调用。所以this默认绑定到window
    var a = 0;
    var obj = {
        a : 2,
        foo:function(){
                function test(){
                    console.log(this.a);
                }
                test();
        }
    }
    obj.foo();//0
    
    var obj = {
        a : 2,
        foo:function(){
                function test(){
                    aaaa = 4;
                }
                test();
        }
    }
    obj.foo()
    window.aaaa // 4
    //思考test绑定到哪里去了呢?window?
    //function test() {}相当于:var test = function(){},所以test只是局部变量,obj.foo()执行完后被销毁
    
    var a = 10;
    function f1(){
      console.log(a);
    }
    
    function bb(){
      var a = 20;
      f1();
    };
    bb() //10
    
    var a = 10;
    function f1(){
      console.log(a);
    }
    
    function bb(){
      var a = 20;
      f1.call(this);
    };
    bb() //10
    

    因为this默认绑定到window

    var a = 10;
    function f1(){
      console.log(a);
    }
    
    function bb(){
      var a = 20;
      f1.call(arguments.callee);
    };
    bb() //10
    

    函数是独立调用,而不是方法调用。所以this默认绑定到window

    function aa(a) {
    a.name = 2;
    
    }
    var b={name:4}
    aa(b);
    b //{name:2}
    

    相关文章

      网友评论

          本文标题:this

          本文链接:https://www.haomeiwen.com/subject/iaymrqtx.html