js的四种用法
1.在一般函数中使用this指代全局对象
function demo(){
this.x = 1;
alert(this.x);
}
demo(); // 1
2.作为对象方法调用,this 指代上级对象
function demo(){
alert(this.x);
} varo = {};
o.x = 1;
o.m = demo;
o.m(); // 1
3.作为构造函数调用,this 指代new 出的对象
function test(){
this.x = 1;
}
varo =new demo();
alert(o.x); // 1//运行结果为1。为了表明这时this不是全局对象,我对代码做一些改变:varx = 2;
function demo(){
this.x = 1;
}
varo =new demo();
alert(x); //2
4..apply 调用 ,apply方法作用是改变函数的调用对象,此方法的第一个参数为改变后调用这个函数的对象,this指代第一个参数
function demo(){
this.x = 1;
}
varo =new demo();
alert(o.x); // 1//运行结果为1。为了表明这时this不是全局对象,我对代码做一些改变:varx = 2;
function test(){
this.x = 1;
}
varo =new demo();
alert(x); //2