JavaScript的关键字 this,函数运行时,自动生成的一个内部对象,只能在函数内部使用。
总的原则:this指的是,调用函数的那个对象。
函数的几种情况和对应的this值:
一. 全局的函数调用
此时this代表全局对象
function test(){
alert(this);
return this;
}
test();//alert([object Window])
//return Window {stop: function, open: function, alert: function, confirm: function, prompt: function…}
二. 作为对象方法的调用
此时this指这个上级对象
function test(){
alert(this.x);
}
var o = {};
o.x = 1;
o.m = test;
o.m(); // 1
三.作为构造函数调用
通过这个函数生成一个新对象(object)。this指这个新对象。
function test(){
this.x = 1;
}
var o = new test();
alert(o.x);//1 var o = {x:1}
四.apply调用
apply()是函数对象的一个方法。对象的一个属性,属性值是函数,那个这个属性可以调用apply()方法启动。
它的作用是改变函数的调用对象,它的第一个参数就表示改变后的调用这个函数的对象。apply()的参数为空时,默认调用全局对象。
function test(){
alert(this.x);
}
var o={};
o.x = 1;
o.m = test;
o.m(); //1
o.m.apply(); //undefined