javascript 中 this指向的理解

this指向应用的场景有以下几个:

  1.函数调用模式    

    this指向的是全局对象

  2.方法调用模式

    this指向的是调用方法的对象

  3.构造器调用模式

    this指向的是new出来的新对象

  4.上下文调用模式   即 call 和 apply 的调用

    this 指向的就是call和apply方法的第一个参数.如果没有传递第一个参数,this的指向就是window对象

 

具体如下:

 

1.函数调用模式

  

  
    window.word = "this is global";
    
    function aa(){   
        console.log(this.word);
    }

    function bb(){
       
        var word = "this is bb";
        aa();
    }
   
     bb();    

  运算结果是 this is global。
  可以看到当作为函数调用的时候,this指向的是window对象。

  即 this指向的就是全局对象

 

 

2.方法调用模式

  

    var car = {
            name : "BMW",
            price : "2000",
            showName:function(){
                console.log(this.name);
            },
            showPrice:function(){
                console.log(this.price);
            }
        }
        car.showName();
        car.showPrice();

 

  
  运算结果是:BMW 2000。
  可以看到 当作为对象方法调用的时候 this指向的是car本身。

  即this指向的就是调用方法的对象

 

3.构造器调用模式

   
     function Car(){
            this.name = "BMW";
            this.price = "2000";
            this.showPrice = function(){
                console.log(this.price);
            }
     }
       var car = new Car();
       car.showPrice();

  
  运算结果是 2000。
  由此可知,这里的this指向的是car这个对象。

 

  即this指向的是new出来的新对象

 

4.上下文调用模式   即 call 和 apply 的调用

 

    function Car(){
        console.log(this.name);
    }
        var bmw = {
            name:"BMW",
            showName:function(){
            Car.apply(this);
        }
    }

    bmw.showName();

 

  运算后得到:BMW 。
  这里通过apply(call也可以)强制把this指向了bmw这个对象。

 

  即this 指向的就是call和apply方法的第一个参数.如果没有传递第一个参数,this的指向就是window对象

 

posted @ 2017-09-19 11:06  ATP1  阅读(121)  评论(0编辑  收藏  举报