this指向问题

要彻底理解JS中的this指向问题,建议多结合一些相关的面试题,理解记忆,不必硬背


关于this问题:只需记住谁调用执行,this就指向谁.也可以理解为"."前边是谁,this就指向谁.例如:window.a(),this指向window

  • 函数的最通常用法,全局性调用,this指向window

      function a(){
        var user = "无可限量";
        console.log(this.user); //undefined
        console.log(this); //Window
    }
    a();//a()==window.a()
    
  • 函数作为对象方法的调用,调用时obj.fn().this指向调用对象

    • 题一
      var obj={
            a:1,
            fn:function  test(){
              console.log(this.a)//1
              console.log(this)//obj
            },
           b:{
                  // a:12,
                tat:function(){
                    console.log(this.a); //undefined
                    conosle.log(this)//this指向b
                }
           }
       }
      obj.fn()
      obj.b.tat()//尽管对象b中没有属性a,这个this指向的也是对象b,因为this只会指向它的上一级对象,不管这个对象中有没有this要的东西。
      
    • 题二
            // fn是被对象b所引用,但是在
            //将fn赋值给变量j的时候并没有执行所以最终指向的是window
               var o = {
                    a:10,
                    b:{
                    a:12,
                    fn:function(){
                        console.log(this.a); //undefined
                        console.log(this); //window
                        }
                  }
            }
            var j = o.b.fn;
            j(); 
      
  • 作为构造函数调用

    new关键字就是创建一个对象实例,用变量obj创建了一个test的实例(相当于复制了一份test到对象obj里面),此时仅仅只是创建,并没有执行,而调用这个函数test的是对象obj,那么this指向的自然是对象obj

     function test() {
       this.x = 1; //this指向实例
      }
    var obj = new test();
    obj.x // 1
    
  • 当this碰到return时

    • 如果返回值是一个对象,那么this指向的就是那个返回的对象.
      //题一:
       function fn(){   
       this.user = "不可限量";  
       return {};  
      }
      var a = new fn;  
      console.log(a.user); //undefined
      //题二:
      function fn() {  
           this.user = '不可限量';  
           return function(){};
      }
      var a = new fn;  
      console.log(a.user); //undefined
      
    • 如果返回值不是一个对象或者返回值是null,那么this还是指向函数的实例
      //题一:
      function fn()  {  
           this.user = '不可限量';  
           return 1;
       }
       var a = new fn;  
       console.log(a.user); //不可限量
       //题二:
       function fn() {  
           this.user = '不可限量';  
           return undefined;
       }
       var a = new fn;  
       console.log(a.user); //不可限量
       //题三:
       function fn() {   
             this.user = '不可限量'; 
             return null;
       }
         var a = new fn; 
       console.log(a.user); //不可限量
      
  • 总结
    1. 全局下this指向window
    2. 给元素的事件绑定方法,方法中this指向被绑定的元素
    3. 函数中的this,看函数执行时看函数前边有没有".",点前面是谁,this指向谁,没有点,this指向window;
    4. 自执行函数中的this永远指向window
    5. 回调函数中的this指向window
    6. 构造函数中的this指向当前的实例
    7. call 、apply、bind改变this指向

除了上面的这些以外,我们还可以自行改变this的指向(call,apply,bind方法).关于这些方法, 请查看 call,apply,bind的应用

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容