关于js中的this指向问题

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值