JavaScript高级知识-this的指向

this的指向

普通函数

  1. 函数在调用时,js会默认给this一个值
  2. this的绑定和定义的位置没有关系
  3. this的绑定和调用方式以及调用位置有关系
  4. this是在运行时被绑定的
    • 默认绑定
    • 隐式绑定
    • 显示绑定
    • new绑定
        function test() {
   
            console.log(this);
        }
        
        // 1. 直接调用
        test(); // window
        
        // 2 通过对象调用
        const obj = {
   
            name: 'obj',
            test: test
        }
        obj.test(); // obj对象
        
        // 3 通过call/bind/apply指定绑定对象调用
        // 下面绑定方式不加String()包裹也可以,js会将其自动转为对象
        test.apply(String('apply')); // String {'apply'} 对象
        test.call(String('call')); // String {'call'} 对象
        test.bind(String('bind'))(); // String {'bind'} 对象
    </script>

在这里插入图片描述

内置函数的this指向

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button>点击</bu>
    <script>
        setTimeout(function () {
     
            console.log('定时器函数:', this); // window
        }, 0);

        const btn = document.querySelector('button');
        btn.onclick = function () {
     
            console.log('btn的点击:', this); // <button>…</button>
        }

        var names = ['tom'];
        names.forEach(function () {
     
            console.log('forEach: ', this); // window
        })
        names.forEach(functio
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值