js中的this指向
this作为js语言的一个关键字,表示函数运行时自动生成的一个内部对象,只能在函数内部使用。
情况1:纯粹的函数调用
function test(){
this.x = 1;
alert(this.x);
}
test(); // 1
//为了证明this就是全局对象,对代码做一些改变
var x = 1;
function test(){
alert(this.x);
}
test(); // 1
//再变
var x = 1;
function test(){
this.x = 0;
}
test();
alert(x); //0
情况2:作为对象方法调用
//函数还可以作为某个对象的方法调用,这时this就指这个上级对象。
function test(){
alert(this.x);
}
var o = {};
o.x = 1;
o.m = test;
o.m(); // 1
情况3:作为构造函数调用
//所谓构造函数,就是通过这个函数生成一个新对象(object)。这时,this就指这个新对象
function test(){
this.x = 1;
}
var o = new test();
alert(o.x); // 1
//为了证明this不是全局对象,对代码做一些改变
var x = 2;
function test(){
this.x = 1;
}
var o = new test();
alert(x); //2
情况4:apply/call调用
var x = 0;
function test(){
alert(this.x);
}
var o={};
o.x = 1;
o.m = test;
o.m.apply(); //0
//apply的参数为空时,默认调用全局对象。若有值,this指向该对象
o.m.apply(o); //1
最后看下几个较为复杂的例子,巩固下理解
//1
var name = "the window";
var object={
name:"my object",
getNameFunc : function(){
return function(){
return this.name;
};
}
};
var func = object.getNameFunc();
console.log(func())//"the window"
//2
var name = "the window";
var object={
name:"my object",
getNameFunc : function(){
var that = this;
return function(){
return that.name;
};
}
};
var func = object.getNameFunc();
console.log(func())//"my object"
//3
var name = "the window";
var object={
name:"my object",
getNameFunc : function(){
return function(){
return this.name;
};
}
};
var obj = {};
obj.name = "obj name"
obj.func = object.getNameFunc();
console.log(obj.func());//"obj name"
总结:
1.函数在被直接调用的时候,其中的this指针永远指向window
2.匿名函数this总是指向window对象
3.谁执行函数,this就指向谁
4.如果函数通过new创建,则this指向新建出来的对象