关于this的用法,网上看到一个非常好的判断方法。

这是网上看见一个判断this的方法,感觉挺不错的。this的定义很简单,它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。然后this指的是,调用函数的那个对象。基本的就那么多,然后通过一些例子来提现。

var someone = {
    name: "Bob",
    showName: function(){
        alert(this.name);
    }
};

var other = {
    name: "Tom",
    showName: someone.showName
}

other.showName();  //Tom

首先根据this的决策树,先判断是否用new调用。否,是否用dot,也就是点,是那么这个this将指向other,看showName()的表达式最后是alert(this.name);那么这个this指向的other,name就是tom。

var name = "Tom";

var Bob = {
    name: "Bob",
    show: function(){
        alert(this.name);
    }
}

var show = Bob.show;
show();  //Tom

还是根据this决策树,判断show(),是否new当然否,是否点,否,那么就指向全局。那么执行这个函数alert(this.name);这时this指向全局。所以是tom。

前面两个都说了来个new的

function Point(x,y){ 
    this.x = x; // this ?
    this.y = y; // this ?
 }
var np=new Point(1,1);
np.x;//1
var p=Point(2,2);
p.x;//error, p是一个空对象undefined
window.x;//2


还是老方法,判断是new构造的。this指向构造函数,np。得到this.x=1,即np.x=1。

 var point = {
    x : 2,
    y : 2,
    moveTo : function(x, y) {
      var moveX = function(x) {
        this.x = x;
      };

      var moveY = function(y) {
        this.y = y;
      };

      moveX(x);//这个this是指向全局的window。因为没点调用和new调用。虽然前面有point,但是到这步已经没有了。
      moveY(y);
    }
  };
  point.moveTo(1, 1);
  console.log(point.x); //==>2
  console.log(point.y) //==>2
  console.log(x); //==>1
  console.log(y); //==>1

这个要稍微复杂一点,之后还有个变行。

var point = { 
x : 0, 
y : 0, 
moveTo : function(x, y) { 
     var that = this; 
    // 内部函数
    var moveX = function(x) { 
    that.x = x; 
    }; 
    // 内部函数
    var moveY = function(y) { 
    that.y = y; 
    } 
    moveX(x); 
    moveY(y); 
    } 
}; 
point.moveTo(1, 1); 
point.x; //==>1 
point.y; //==>1

在执行moveX(x)之前this是指向point的将var that = this; 之后的用that。

http://www.cnblogs.com/isaboy/p/javascript_this.html



猜你喜欢

转载自www.cnblogs.com/manu-yyj/p/9131348.html