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

相关推荐
不听话坏11 分钟前
Ignition篇(下 一) 动态执行前的事情
开发语言·前端·javascript
likeyi0722 分钟前
require 和 import的区别
开发语言·前端
pany1 小时前
做 AI 友好的开源 Vue3 模板 🌈
前端·vue.js·ai编程
小二·1 小时前
React 19 + Next.js 15 现代前端开发实战:App Router / Server Components / 流式渲染
前端·javascript·react.js
谙忆10242 小时前
前端图片直传对象存储:OSS/S3 预签名 URL、STS 临时凭证与回调校验
前端
CHNE_TAO_EMSM4 小时前
Android studio 打开文件时自动下载源码
前端·javascript·android studio
一孤程4 小时前
Airtest自动化测试第五篇:小程序与Web测试——跨平台自动化全覆盖
前端·自动化测试·小程序·自动化·测试·airtest
IT_陈寒4 小时前
SpringBoot自动配置不是你以为的那样的智能
前端·人工智能·后端
yume_sibai5 小时前
大屏数据可视化 - 边框红绿呼吸灯实现详解
前端·信息可视化·typescript
竹林8186 小时前
从 ethers.js 迁移到 Viem:一个签名验证 Bug 让我彻底放弃旧爱
javascript