this的分析

时间:2023-03-09 16:52:24
this的分析

this是js中的一个关键字,当函数运行时,会自动生成的一个对象,只能在函数内部使用。随着函使用场合不同,this值会变化,但是始终指向调用函数的那个对象。

1.纯粹的函数调用

function box(){
console.info(this); //window
this.x ="box";
}
box();
console.info(x); //box

以上说明单纯调用函数,函数中的this就代表window。我会在写两个小栗子:

var x=1;
function box(){
console.info(this.x); //
}
box();
var x=1;
function box(){
this.x = 2;
}
box();
console.info(x);//

2.作为某一个对象的方法

当函数作为某一个对象的方法调用时,this就代表这个对象

接下来的三个栗子是最常用的方法

function test(){
console.info(this.x);
}
var o = {};
o.x = 1;
o.m=test;
o.m(); //1,this代表o

 

var o = {};
o.x = 1;
o.m =function(){
console.info(this.x);
}
o.m();//1,this代表o

  

var o={
x:1,
m:function(){
console.info(this.x)
}
}
o.m();//1 this代表o

  

3.作为构造函数调用

也就是通过构造函数生成一个新对象,this代表这个新对象,这个很常用

function box(){
this.x = 1;
}
var box1 = new box();
console.info(box1.x);//1 this代表box1这个对象

4.apply调用

apply是用来改变调用函数的对象的方法,第一个参数代表改变后的对象,剩下的参数代表传入的参数

var x = 0;
function box(){
console.info(this.x);
}
var o={
x:1,
m:box
}
o.m();//1
o.m.apply(); //0
o.m.apply(o); //1

 注意当apply什么也传时,代表传了window