js中this关键字的指向问题

this的指向问题:

本文详细解释this关键字在不同场景下的指向问题。


this的概念

    this是一个关键字
        主要介绍函数内的this 
        概念:
            函数内的this和函数在哪定义的没有关系,和函数怎么定义也没有关系。

           *! 只看函数如何被调用的(箭头函数除外)
<style>
        div {
            width: 200px;
            height: 200px;
            background-color: red;
        }
    </style>
</head>
    <div id="div"></div>
    <script>
     
        function fn() {
              console.log(this);
              console.log("================");
          } 
        // 普通调用
         fn()//this 指向的是window

        // 对象调用
         var obj = {
             a: 12,
             fun: fn,
             name: 'jack'
         } 
         obj.fun()//this指向的是obj
         obj['fun']()

        // 数组调用
        var arr = [fn, 12, 'tom']
        arr[0]()//this指向的是arr

        // 定时器调用
        setTimeout(function () {
            fn()//this指向的是window
        }, 500);

        setInterval(function () {
            fn()//this指向的是window
        }, 500); 

        setTimeout(fn(), 90)//this指向的是window

        // 事件处理函数
        div.onclick = fn//this指向的是事件源
        // 0级绑定事件
         div.onclick = function () {
             console.log(this);//this指向的是***事件源***,不是事件目标。
            console.log('=============');
         }

        // 二级绑定事件
        div.addEventListener('mousemove', function () { console.log(this); })//this指向的是事件源

        // 自执行函数
       ;(function () {
            console.log('自执行函数');
            console.log(this);//this指向的是window
        })() 
       </script>
    // 总结
    /*
      普通调用、定时器调用、自执行调用----this指向的是window
      对象调用------this指向的是对象名
      数组调用------this指向的是数组名
      事件处理函数调用------this指向的是事件源 */
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值