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也是可以的

相关推荐
牛奶1 小时前
2026年大模型怎么选?前端人实用对比
前端·人工智能·ai编程
牛奶1 小时前
前端人为什么要学AI?
前端·人工智能·ai编程
Kagol4 小时前
🎉OpenTiny NEXT-SDK 重磅发布:四步把你的前端应用变成智能应用!
前端·开源·agent
GIS之路5 小时前
ArcGIS Pro 中的 notebook 初识
前端
JavaGuide5 小时前
7 道 RAG 基础概念知识点/面试题总结
前端·后端
ssshooter5 小时前
看完就懂 useSyncExternalStore
前端·javascript·react.js
格砸6 小时前
从入门到辞职|从ChatGPT到OpenClaw,跟上智能时代的进化
前端·人工智能·后端
Live000007 小时前
在鸿蒙中使用 Repeat 渲染嵌套列表,修改内层列表的一个元素,页面不会更新
前端·javascript·react native
柳杉7 小时前
使用Ai从零开发智慧水利态势感知大屏(开源)
前端·javascript·数据可视化