this是Javascript语言的一个关键字。
它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。比如,
function test(){
this.x = 1;
}
随着函数使用场合的不同,this的值会发生变化。但是有一个总的原则,那就是this指的是,调用函数的那个对象。
下面分四种情况,详细讨论this的用法。
情况一:纯粹的函数调用
this的值指向window,准确的说,this为null但被解释成window,在ESMA标准中,如果this为null,则解释成underfined。
请看下面这段代码,它的运行结果是1。
function test(){
this.xx = 1;
alert(this.xx);
}
test();
为了证明this就是全局对象,我对代码做一些改变:
var x = 1;
function test(){
alert(this.x);
}
test();
运行结果还是1。再变一下:
var x = 1;
function test(){
this.x = 2;
alert(this.x);
}
test(); //x = 2;
情况二:作为对象方法的调用
this指向其调用那一刻的调用者,不管被调用函数,申明时属于方法,还是函数。
var obj = {
xx:99,
yy:888,
t:function(){
alert(this.xx);
}
}
obj.t(); //99
var dog = {xx:'xiaobao'};
dog.t = obj.t;
dog.t(); //xiaobao
show=function(){
alert('show' + this.xx);
}
dog.t = show;
dog.t(); //showxiaobao
情况三:作为构造函数调用
所谓构造函数,就是通过这个函数生成一个新对象(object)。这时,this就指这个新对象。
function test(name,age){
this.name = name;
this.age = age;
this.bark = function(){
alert('i am' + this.name +'!');
}
}
var dog = new test('xiaobao','22');
dog.bark(); //i am xiaobao
//下面返回什么?
function pig(){
this.age = 99;
return 'abc';
}
var big = new pig(); //这里得到的是pig对象,因为函数作为构造函数运行时,return值忽略,还是返回对象
console.log(big); //Object { age: 99 }
情况四 函数通过call、apply调用
apply()是函数对象的一个方法,它的作用是改变函数的调用对象,它的第一个参数就表示改变后的调用这个函数的对象。因此,this指的就是这第一个参数。
function t(num){
alert('我的真实年龄是'+this.age);
alert('但我一般告诉别人我'+(this.age+num));
}
var human = {name:'lisi',age:28};
human.t = t;
human.t(-10); //this指向human
//接下来,我们不把t赋为human的属性,也能把this指向human
var wangwu = {name:'wangwu',age:30};
t.call(wangwu,5); //fn函数.call(对象,参数1,参数2.。。。参数n);
网友评论