javascript 入门——this属性的理解!

  JavaScript中函数的this对象是函数在执行时所处的作用域(例:当在网页的全局作用域中调用函数时,this对象引用的就是window)。

例:

window.color = "red";
var o = {color:"red"};
function sayColor(){
    alert(this.color);    
}
sayColor();      //"red"
o.sayColor = sayColor;
o.sayColor();   //"blue"

  上面的sayColor()是在全局作用于中定义的,它引用this对象。由于在调用之前this的值并不确定。因此this可能在代码执行的过程中引用不同的对象。当在全局作用域中调用sayColor()时,this引用的是全局对象window;即对this.color求值会转换成对window.color求值。所以结果是“red”。而当把这个函数赋给对象o并调用o.sayColor()时,this引用的对象o,因此this.color求值会转换成对o.color求值。结果就是“blue”.

  In JavaScript, as in most object-oriented programming languages, this is a special keyword that is used within methods to refer to the object on which a method is being invoked.

  The this keyword is relative to the execution context, not the declaration context.(this与执行环境而不是声明环境有关)

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

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

other.showName();  //Tom

  this在some.showName中声明,但是在other.showName中执行,因此other.showName();执行结果为Tom。

  在没有明确执行的当前对象时,this一般指全局对象,即window。