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

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

   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()

 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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值