this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁,实际上this的最终指向的是那个调用它的对象
情况1:
如果一个函数中有this,但是它没有被上一级的对象所调用,那么this指向的就是window(这里需要说明的是在js的严格版中this指向的不是window)
function a(){
var user = "hellow";
console.log(this.user); //undefined
console.log(this); //Window
}
a();
function a(){
var user = "hellow";
console.log(this.user); //undefined
console.log(this); //Window
}
window.a();
情况2:
如果一个函数中有this,这个函数有被上一级的对象所调用,那么this指向的就是上一级的对象。
var o = {
user:"hellow",
fn:function(){
console.log(this.user); //hellow
}
}
o.fn();
通过事件绑定的方法, 此时 this 指向 绑定事件的对象
var xx = document.getElementById("xx");
xx.onclick = function() {
console.log(this); // xx
}
定时器函数, 此时 this 指向 window
setInterval(function () {
console.log(this); // window
}, 1000);
情况3:
如果一个函数中有this,这个函数中包含多个对象,尽管这个函数是被最外层的对象所调用,this指向的也只是它上一级的对象,
var o = {
user:"hellow",
fn:function(){
console.log(this.user); //hellow
}
}
window.o.fn();
var o = {
a:10,
b:{
a:12,
fn:function(){
console.log(this.a); //12
}
}
}
o.b.fn();
var o = {
a:10,
b:{
// a:12,
fn:function(){
console.log(this.a); //undefined
}
}
}
o.b.fn();
还有一种比较特殊的情况
var o = {
a:10,
b:{
a:12,
fn:function(){
console.log(this.a); //undefined
console.log(this); //window
}
}
}
var j = o.b.fn;
j();
这里this指向的是window,是不是有些蒙了?其实是因为你没有理解一句话,这句话同样至关重要。
this永远指向的是最后调用它的对象,也就是看它执行的时候是谁调用的,例子4中虽然函数fn是被对象b所引用,但是在将fn赋值给变量j的时候并没有执行所以最终指向的是window
情况4:
new操作符会改变函数this的指向问题
为什么this会指向a?
首先new关键字会创建一个空的对象,
然后会自动调用一个函数apply方法,将this指向这个空对象,
这样的话函数内部的this就会被这个空的对象替代。
function fn(){
this.num = 1;
}
var a = new fn();
console.log(a.num); //1
情况5:
当this碰到return时
如果返回值是一个对象,那么this指向的就是那个返回的对象
function fn(){
this.user = 'hellow';
return {};
}
var a = new fn;
console.log(a.user); //undefined
function fn(){
this.user = 'hellow';
return function(){};
}
var a = new fn;
console.log(a.user); //undefined
如果返回值不是一个对象那么this还是指向函数的实例
function fn(){
this.user = 'hellow';
return 1;
}
var a = new fn;
console.log(a.user); //hellow
function fn(){
this.user = 'hellow';
return undefined;
}
var a = new fn;
console.log(a.user); //hellow
console.log(a); //fn {user: "hellow"}
还有一点就是虽然null也是对象,但是在这里this还是指向那个函数的实例,因为null比较特殊。
function fn(){
this.user = 'hellow';
return null;
}
var a = new fn;
console.log(a.user); //hellow
Comments | NOTHING