随着函数使用场合的不同,this的值会发生变化。但是有一个总的原则,那就是this指向的是,调用函数的那个对象。
有几种情况:
1、全局函数中的this
函数的最通常的用法,属于全局性调用,示例代码:
var x = 1;
function test(){
this.x = 0;
alert(x);
}
test(); //结果为0
因为test函数不属于具体的哪个对象,因此是全局的,所以this指向的就是window,即全局对象,因此this.x改变的是全局变量x。
2、具体对象方法中的this
当函数是具体的某一对象的方法时,函数里的this指向该对象。示例代码:
var x=1;
var obj= {};
obj.x= 0;
obj.m= function(){
alert(this.x);
};
obj.m();// 0
因为方法m是obj对象专有的,所以方法内的this指向了obj,alert出来的便是obj的x,结果为0。
项目代码讲解:
这里为什么要用self保存this呢?因为我们希望的是,获取完活动信息后,将actData赋值给全局变量actInfo,这样后面各个函数里我们才能用actInfo。因为on绑定的方法是属于app这个对象的,所以当执行on方法时,this指向就发生了改变,由指向全局变为指向对象app了,如果在里面用this.actInfo的话,只是将活动信息给了app里的属性actInfo,其他函数是用不了的。为了赋值给全局变量,只能采取一开始保存this指向的方法。
3、在构造函数中的this
通过构造函数生成一个新对象(object)时,this就指这个新对象。示例代码:
function Person(){
this.x = 1;
}
var obj = new Person();
alert(obj.x); // 1
通过Person函数创建了一个新对象,所以this指向的是新对象obj,所以obj的x是1。
4、特殊用法
当函数是箭头函数时,箭头函数没有它自己的this值,箭头函数内的this值继承自外围作用域。示例代码:
可以看到,这里与之前的代码不一样,没有用额外的变量保存this,是因为maintab里绑定的函数是箭头函数,此时这里面的this是继承这个函数外部的this,因为createMainTab方法是全局的方法,this是指向全局的this,所以maintab里的this也是指向全局的this,所以这里调用renderOverallContent方法和renderDailyTab方法直接用的this。
5、修改this的指向
通过apply方法或者call方法,可以改变this的指向。示例代码:
在这个例子中,obj1的x赋值为1,obj2的x赋值为2,调用obj2的m方法,m中的this本应指向obj2,但用了apply方法后,this指向obj1,所以运行结果为1。
Example:
1、
var x = 2;
function test(){
var x = 1;
console.log(this.x); //2,this指向调用test()函数的对象,为window
console.log(x); //1,局部变量x
}
test();
2、
var x = 2;
function Test(){
this.x = 1;
}
var o = new Test(); //此时this指向o
console.log(o.x); //1
Test(); //this指向全局,此时全局变量x值由2变为1
x = x + 5; //1+5=6
console.log(x);//6
o.x = 3;//o对象的x属性值变为3
console.log(o.x);//3
3、
var Foo = {};
Foo.method = function(){
var test = function(){
console.log(this);
}
test(); // Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …} 即使这个test函数写在内部,但是本质上还是属于Window
};
Foo.method();
4、
var myObject = {};
myObject.value = 3;
myObject.double = function () {
var helper = function () {
this.value += this.value;
}
helper(); //同上题,调用helper()的是Window对象
}
myObject.double();
console.log(value); //NaN, 而全局上下文里并没有定义value,所以是undefined+undefined为NaN
5、
var myObject = {};
myObject.value = 3;
myObject.double = function () {
var that = this; //this指向myObject这个对象,用that保存起来
var helper = function () {
that.value += that.value; // 3+3
}
helper();
}
myObject.double();
console.log(myObject.value); //6