Object.prototype.toString为什么要加.call

问题1:为什么是Object.prototyp不能直接arr.toString

js 复制代码
   console.log("arr.toString()", arr.toString());

    const num = 123;
    console.log("num.toString()", num.toString());

	  const fun = () => {
      console.log("fun");
    };
    console.log("fun.toString()", fun.toString());


    const obj = { name: "slx", age: 3434 };
    console.log("obj.toString", obj.toString());

因为Array和Function等的toString方法都重写了,只有Object的没有被重写,所以只有Object.prototype才可以判断数据类型

问题2:为什么后面要加call()

js 复制代码
 const arr = [1, 2, 3];
    console.log(
      " Object.prototype.toString(arr)",
      Object.prototype.toString(arr)
    );
    console.log(
      " Object.prototype.toString.call(arr)",
      Object.prototype.toString.call(arr)
    );

如果不加.call()的话,this指向为Object,Object的数据类型自然是Object,所以不管判断啥都是Object;

添加call之后,改变this指向arr.才能得到正确的类型结果

理论上使用apply也是可以的

相关推荐
鹏北海2 小时前
JSBridge 原理详解
前端
孟健2 小时前
我的网站被黑了:一天灌入 227 万条垃圾数据,AI 写的代码差点让我社死
前端
anOnion2 小时前
构建无障碍组件之Checkbox pattern
前端·html·交互设计
IT枫斗者4 小时前
IntelliJ IDEA 2025.3史诗级更新:统一发行版+Spring Boot 4支持,这更新太香了!
java·开发语言·前端·javascript·spring boot·后端·intellij-idea
N***p3654 小时前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
NGC_66114 小时前
二分查找算法
java·javascript·算法
享誉霸王5 小时前
15、告别混乱!Vue3复杂项目的规范搭建与基础库封装实战
前端·javascript·vue.js·前端框架·json·firefox·html5
a1117766 小时前
飞机躲避炸弹 网页游戏
前端·开源·html·threejs
夏乌_Wx6 小时前
mybash:简易 Shell 实现的设计思路与核心模块解析
linux·服务器·前端
滕青山6 小时前
URL编码/解码 核心JS实现
前端·javascript·vue.js