Javascript的this用法

this总是指向调用函数的那个对象

纯粹的函数调用

this指向window

1
2
3
4
5
6
var x = 1;
function test(){
 this.x = 0;
}
test(); // 相当于window.test()
alert(x); //0

作为对象方法的调用

this 指向这个上级对象

1
2
3
4
5
6
7
function test(){
alert(this.x);
}
var o = {};
o.x = 1;
o.m = test;
o.m(); // 1

作为构造函数调用

所谓构造函数,就是通过这个函数生成一个新对象(object)。这时,this就指这个新对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
function Test(){
  this.x = 1;
}
var o = new Test();
alert(o.x); // 1

// 为了表明这时this不是全局对象,我对代码做一些改变:
var x = 2;
function test(){
this.x = 1;
}
var o = new test();
alert(x); //2

apply调用

pply()是函数对象的一个方法,它的作用是改变函数的调用对象,它的第一个参数就表示改变后的调用这个函数的对象。因此,this指的就是这第一个参数。

1
2
3
4
5
6
7
8
var x = 0;
function test(){
alert(this.x);
}
var o={};
o.x = 1;
o.m = test;
o.m.apply(); //0

apply()的参数为空时,默认调用全局对象。因此,这时的运行结果为0,证明this指的是全局对象。

如果把最后一行代码修改为
  o.m.apply(o); //1

运行结果就变成了1,证明了这时this代表的是对象o。