大学生必备JS知识点:this指向问题和三种改变this指向(call,apply和bind)

1.this指向的几种情景

1.1  this在全局中是window

<script>
   //第一种情况 this在全局中 指向的是window
   console.log(this)  
</script>

1.2 this在function f1()中 f1是谁 this指向谁

   function f1(a){
       console.log(this) //window
   }
   f1(2)
   var o = {
        a: 10,
        b: {
            a: 12,
            fn: function() {
                console.log(this.a); //   结果为多少    undefined   
                console.log(this); //     结果为多少   window
            }
        }
    }
    var j = o.b.fn;
    j();

1.3 事件绑定的function函数的this

<body>
    <button id="btn"> 点击 </button>
</body>

<script>
   var btn1 = document.querySelector('#btn')
   btn1.onclick = function() {
      console.log(this) //就是btn1标签
}

</script>

1.4 事件绑定的箭头函数的this指向window

<body>
    <button id="btn"> 点击 </button>
</body>

<script>
   var btn1 = document.querySelector('#btn')
   btn1.onclick = ()=> {
      console.log(this) //window
}

</script>

1.5 定时器 this如果是匿名函数,那么this指向window

<script>
 setTimeout(() => {
        console.log(this); //window
    }, 123);
</script>

1.6 通过new Function 来定义的函数 this指向window

var f2 = new Function("var a=10; var b=20; console.log(this);return a+b;")
    f2() //window

1.7  如果回调函数是箭头函数,箭头函数的this指向的是上下文的this

<body>
    <button id="btn"> 点击 </button>
</body>
<script>
   var btn1 = document.querySelector('#btn')
   btn1.onmouseenter = function() {
        setInterval(() => {
            console.log(this); //指的是上下文的this 
        }, 1000)
    }
</script>

2.改变this指向问题

    1.call() apply() 第一个参数要写this要指向的对象 然后第二个参数是传递的值(如果值是多个用[a,b,c])apply是数组,而call是参数列表

    2.call() 和 apply() 是直接调用函数

    3.bind() 只绑定this要指向的对象 然后 调用需要自己写才会调用 js中 多次bind是无效的

           例如 var a = bar.bind(foo).bind(fww).bind(fcc) this只会指向 foo对象

今天也有在认真学习 虽然是星期六但是我在集中隔离就哈哈哈哈  为什么呢!!因为出去看病然后郑州忽然有疫情不让回去了,只能回家,然后被接走集中隔离去了!

郑州加油!!!中国yyds 听说有个nb的药!越来越厉害了国家

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

今天也在努力学

很感谢!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值