最可靠的基础方案是Object.prototype.toString,它能稳定识别所有内置对象类型并兼容跨环境;typeof适用于原始类型和函数的快速判断;instanceof仅在同执行上下文且原型未被破坏时用于自定义类识别。

单纯依赖 typeof 无法准确识别大多数引用类型,instanceof 受原型链和跨执行上下文限制,而 Object.prototype.toString 是最可靠的基础方案——但“完美”判定不靠单一方法,而在于分层组合、按需补足。
用 Object.prototype.toString 统一获取内部标签
所有内置对象(包括数组、正则、日期、Map 等)在调用 Object.prototype.toString.call(x) 时,都会返回形如 "[object Type]" 的字符串。这是 ECMAScript 规范定义的 [[Class]] 内部属性的标准化暴露方式,稳定且跨环境兼容。
建议封装为一个基础识别函数:
function getType(value) {
return Object.prototype.toString.call(value).slice(8, -1);
}
// getType([]) → "Array"
// getType(/a/) → "RegExp"
// getType(new Set()) → "Set"
// getType(null) → "Null"
// getType(undefined) → "Undefined"
注意:它对 null 和 undefined 也有效,无需额外判断;但对自定义类实例,默认返回 "Object",需配合其他手段增强。
用 typeof 精准区分原始类型与函数
typeof 在原始类型上表现唯一且高效:"string"、"number"、"boolean"、"symbol"、"bigint"、"undefined" 都不会误判;对函数返回 "function",这是 toString 无法替代的优势(后者对函数也返回 "Function",但语义不如 typeof 直观)。
实际使用中可优先用 typeof 快速分流:
- 若
typeof x === "object"或"function",再交由toString进一步细分 - 若
typeof x === "string"等原始类型,直接确认,不走toString - 避免对
null使用typeof(它错误返回"object"),统一交给toString
用 instanceof 补足自定义类与跨框架场景
Object.prototype.toString 对自定义构造函数一律返回 "Object",此时需 instanceof 判断具体类身份。但它有明显局限:
- 依赖原型链,若手动修改
prototype或使用Object.create(null),会失效 - 在 iframe 或不同 window 中创建的数组、正则等,
instanceof Array返回false,而toString仍正确
因此推荐策略是:先用 toString 确认是否为某类内置对象;对自定义类,仅在明确同一执行上下文且原型未被破坏时使用 instanceof;若需跨 iframe 安全判断,可用 toString + 构造函数名比对(需确保构造函数名未被压缩)或 constructor?.name 辅助。
组合策略示例:一个实用的类型检查工具
不追求“一刀切”的完美函数,而是按用途分层设计:
// 基础类型名(最稳) const typeOf = (val) => Object.prototype.toString.call(val).slice(8, -1); // 是否为数组(兼顾 iframe) const isArray = (val) => Array.isArray(val) || typeOf(val) === "Array"; // 是否为 Promise(不能只靠 toString,因 polyfill 可能无标准标签) const isPromise = (val) => val != null && (typeof val.then === "function" && typeof val.catch === "function") || typeOf(val) === "Promise"; // 自定义类实例(带 fallback) const isMyClass = (val) => val instanceof MyClass || (val?.constructor?.name === "MyClass");
关键点:以 toString 为基石,用 typeof 加速原始类型,用 instanceof 或特征属性(如 .then)补充语义化判断——没有银弹,只有适配场景的组合。

















