Javascript的this关键字

1.this和对象的关系

var person = {
name:'Theo Wong',
gender:'male',
getName:function(){
console.log(person.name);    //person.name=this.name;
}
};
person.getName();

this永远指向的是函数对象的所有者!上面的例子中getName的所有者是person对象,所以this指代的是person。

2.this和全局对象

所以在全局函数中,this指代的是window对象(除非使用new,call,apply方法来改变this的指代关系)

var a = 1;
function foo(){
var b = 2;
console.log(this.a+b);//3
}
foo();

3.函数构造器中的this

当函数作为构造器使用new关键字实例化时,this的指代关系又是怎样的呢?看下面的代码:

var Person = function(){
	this.name = 'Theo Wong';
}
var person = new Person();
console.log(person.name);

new执行过程会首先执行Person的构造器[[construct]],然后在调用[[call]]方法给this赋值,这个执行过程可以简单理解为三步

  1. 首先建立一个空的对象object,类似var obj={}
  2. 然后将空对象使用Person的call操作,类似Person.call(obj)
  3. 执行完Person之后再return this,完成new过程,赋值给person变量

所以经过new加工过的函数,this的函数调用者是Person本身,而不是window了

4.嵌套函数中的this

在嵌套函数中,this的指代关系有会是怎样的呢?看下面的代码:

var myObject = {
  func1:function() {
     console.log(this); //myObject
     var func2=function() {
        console.log(this); //window
        var func3=function() {
           console.log(this); //window
        }();
     }();
  }
}; 
myObject.func1();

在嵌套函数中,由于嵌套函数的执行上下文是window,所以this指代的是window对象,其实这是ECMA-262-3的一个bug,在最新的ECMA-262-5中已经修复。

5.

 

 

 

 

 

 

 

 

 

 

 

posted @ 2012-09-26 16:20  hlp鹏  阅读(124)  评论(0编辑  收藏  举报