this的用法

this是Javascript语言的一个关键字。
它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。
随着函数使用场合的不同,this的值会发生变化。但是有一个总的原则,那就是this指的是,调用函数的那个对象。
下面分四种情况,详细讨论this的用法:

  • 纯粹的函数调用

这是函数的最通常用法,属于全局性调用,因此this就代表全局对象Global。

function test(){
    this.x = 1;
    alert(this.x);
}
test(); //1

为了证明this就是全局对象,对代码做一些调整:

var x = 1;
function test(){
    alert(this.x);
}
test(); //1

再调整一下:

var x = 1;
function test(){
    this.x = 0;
}    
test();
alert(x); //0
  • 作为对象方法的调用

函数还可以作为某个对象的方法调用,这时this就指这个上级对象:

function test(){
    alert(this.x);
}
var one = {};
one.x = 1;
one.m = test;
one.m(); //1
  • 作为构造函数调用

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

function test(){
    this.x = 10;
}
var one = new test();
alert(one.x); //10

为了表明这时this不是全局对象,对代码做了一些调整:

var x = 2;
function test(){
    this.x = 10;
}
var one = new test();
alert(x); //2

表明全局变量x的值根本没变。

  • apply&call调用

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

var x = 0;
function test(){
    alert(this.x);
}
var one = {};
one.x=10;
one.m = test;
one.m.apply(); //0

apply()的参数为空时,默认调用全局对象。因此,这时的运行结果为0,证明this指的是全局对象。
如果把最后一行代码修改为:

one.m.apply(one); //10

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

当一个函数的函数体中使用了this关键字时,通过所有函数都从Function对象的原型中继承的call()方法和apply()方法调用时,它的值可以绑定到一个指定的对象上。

function add(c, d){
  return this.a + this.b + c + d;
}

var o = {a:1, b:3};

// The first parameter is the object to use as 'this', subsequent parameters are passed as 
// arguments in the function call
add.call(o, 5, 7); // 1 + 3 + 5 + 7 = 16

// The first parameter is the object to use as 'this', the second is an array whose
// members are used as the arguments in the function call
add.apply(o, [10, 20]); // 1 + 3 + 10 + 20 = 34    

使用 call 和 apply 函数的时候要注意,如果传递的 this 值不是一个对象,JavaScript 将会尝试使用内部 ToObject 操作将其转换为对象。因此,如果传递的值是一个原始值比如 7 或 ‘foo’ ,那么就会使用相关构造函数将它转换为对象,所以原始值 7 通过new Number(7)被转换为对象,而字符串’foo’使用 new String(‘foo’) 转化为对象,例如:

function bar() {
  console.log(Object.prototype.toString.call(this));
}

bar.call(7); // [object Number]