object.prototype.tostring.call 能准确检测内置类型,因其调用原始未覆盖方法返回"[object type]"格式字符串,而直接调用对象tostring会因重写导致误判;typeof则无法区分数组、null等具体类型。

JavaScript 中用 Object.prototype.toString 检测类型,核心是借用原生方法并正确绑定 this,从而避开内置类型(如 Array、Date、RegExp 等)被重写 toString 方法导致的误判问题。
为什么不能直接调用对象的 toString()?
很多内置对象(比如数组、日期、正则)都重写了自己的 toString 方法:
-
[1, 2].toString()→"1,2"(不是"[object Array]") -
new Date().toString()→ 类似"Mon Apr 01 2024..." -
/abc/.toString()→"/abc/"
这些返回值无法用于准确判断类型。而 Object.prototype.toString 是最原始、未被覆盖的版本,它会返回标准格式字符串:"[object Type]"。
标准用法:call 或 apply 借用
必须把目标值作为 this 绑定给 Object.prototype.toString:
-
Object.prototype.toString.call([])→"[object Array]" -
Object.prototype.toString.call(new Date())→"[object Date]" -
Object.prototype.toString.call(null)→"[object Null]" -
Object.prototype.toString.call(undefined)→"[object Undefined]" -
Object.prototype.toString.call(123)→"[object Number]"
封装成通用类型检测函数
提取括号内的类型名,更便于使用:
function getType(obj) {
return Object.prototype.toString.call(obj).slice(8, -1);
}
// 使用示例:
getType([]); // "Array"
getType(/abc/); // "RegExp"
getType(new Set()); // "Set"
getType(new Map()); // "Map"
getType(globalThis); // "global"
注意:ES6+ 新增的类型(如 Promise、BigInt、Symbol)也支持,返回对应名称(如 "Promise"、"BigInt"、"Symbol")。
和 typeof 的区别与适用场景
typeof 简单但能力有限:
-
typeof []→"object"(无法区分数组) -
typeof null→"object"(历史 bug) -
typeof new Date()→"object"(无法识别具体构造器)
Object.prototype.toString.call 更精确,适合需要明确内置类型名的场景,比如序列化、类型校验、工具库中的 isArray / isDate 实现。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











