js开发中多多少少都会遇到this指向问题,多少会有些懵圈,只要记住一句核心的话,哪个对象调用函数,this就指向哪个对象
调用函数一般有以下这么多中情况:
1,普通函数调用
毫无疑问,此时this指向的是window对象
var username='守候'
function fn(){
alert(this.username);//守候
}
fu();
//---------------
window.username='守候'
function fn(){
alert(this.username);//守候
}
fn();
//可以理解为
//window.fn();
2,对象中的函数调用
这个不难理解,哪个对象调用这个函数,this就指向哪个对象
window.b=2222
let obj={
a:111,
fn:function(){
alert(this.a);//111
alert(this.b);//undefined
}
}
obj.fn();
3,构造函数调用
构造函数中的this 指向的就是构造函数本身
let TestClass=function(){
this.name='111';
}
let subClass=new TestClass();
subClass.name='守候';
console.log(subClass.name);//守候
let subClass1=new TestClass();
console.log(subClass1.name)//111
4,apply call 调用
call apply会改变传入函数的this,this会指向call的参数
let obj1={
a:222
};
let obj2={
a:111,
fn:function(){
alert(this.a);
}
}
obj2.fn.call(obj1);
5,箭头函数:
箭头函数没有绑定this,因此在箭头函数中使用this,取到的是外部函数的this
第一种情况:setTimeOut()中传入的是普通函数,所以this会指向window对象,而在window对象中没有window.a这个属性
因此console的undefind
第二种情况: setTimeOut()传入的是箭头函数,箭头函数没有this,因此就去外层寻找this,指向了obj对象
let obj={
a:222,
fn:function(){
setTimeout(function(){console.log(this.a)})
}
};
obj.fn();//undefined
let obj={
a:222,
fn:function(){
setTimeout(()=>{console.log(this.a)});
}
};
obj.fn();//222