JavaScript中各种情况下this的指向问题(全面总结篇)

一、this–>undefined

ES6的严格模式中,如果调用函数中的this或者顶层this将会指向undefined。

<script type="module">
      function fn(){
   
          console.log(this);
      }
      fn(); //undefined
</script>
<script type="module">
      console.log(this); //undefined
</script>

二、this–>window

  1. 非严格模式中函数或者顶层中调用this,会被指向window
  2. 回调函数中默认this的指向是window
  3. 当使用call、apply、bind时,如果带入的第一个参数是null或者undefined,this默认会被指向window

三、this–>上下文环境中的this

  1. 箭头函数
      var obj={
   
          a:function(){
   
              setTimeout(()=>{
   
                  this.b();//this就是当前箭头函数外的上下文环境中this的指向
                  // setTimeout外面的this是什么这个箭头函数中的this就是什么
              },500)
              document.addEventListener("click",e=>{
   
                  this.clickhandler(e)
                  // 这里的this指向addEventListener函数外上下文环境中this的指向
              });
          },
          b:function(){
   
              console.log("aaa");
          },
          clickhandler:function(e){
   

          }
      }
  1. 对象的属性中this也是上下环境中this的指向
      var c = 20;
      var obj = {
   
        c: 10,
        a: this.c,
        b: function () {
   
          console.log(this.a);
        },
      }</
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值