gpt4 book ai didi

javascript - 将 toString 调用与 toString 进行比较

转载 作者:行者123 更新时间:2023-12-02 16:14:40 27 4
gpt4 key购买 nike

return toString.call(obj)return obj.toString() 有什么区别?

我通常会找到具有这些不同风格的代码

最佳答案

toString.call(obj) 返回对象的类型,而 obj.toString() 返回对象的字符串表示形式或对象的类型(如果不存在)还没有实现这个功能。

示例:

var a = [5];
a.toString() // "5"
toString.call(a) // "[object Array]"

更多详细信息可以在 MDN 上找到:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

使用 toString() 检测对象类:

var toString = Object.prototype.toString;

toString.call(new Date); // [object Date]
toString.call(new String); // [object String]
toString.call(Math); // [object Math]

// Since JavaScript 1.8.5
toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]

UnderscoreJS 使用 toString.call(obj) 而不是 typeOf,因为它更快:

_.isNumber = function(obj) {
return toString.call(obj) == '[object Number]';
};

关于javascript - 将 toString 调用与 toString 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29795330/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com