typeof适合检测原始类型和函数,但对null和所有对象均返回"object";instanceof基于原型链检测引用类型,跨iframe失效。

直接说结论: typeof 适合检测原始类型(string、number、boolean、undefined、symbol、bigint)和函数,但对 null 和所有对象(包括数组、正则、日期等)都返回 "object";instanceof 检测的是对象是否在某个构造函数的原型链上,只适用于引用类型,且跨 iframe 会失效。
为什么 typeof null 是 "object"?
这是 JavaScript 最早版本的历史 bug,V8 等引擎沿用至今以保持兼容。它本质是底层把 null 的类型标签误设为对象类型(0),而 typeof 直接读取该标签。
实际开发中别信 typeof x === "object" 就能判断“是不是对象”——它连 null 都过不了关。
- 要安全判断普通对象,用
Object.prototype.toString.call(x) === "[object Object]" - 要区分
null,必须显式写x === null - 数组、正则、Date 等都通不过
typeof,一律返回"object"
instanceof 的原理和致命限制
instanceof 的行为等价于:沿着左操作数的 __proto__ 链向上查找,看能否找到右操作数的 prototype 对象。
立即学习“Java免费学习笔记(深入)”;
这意味着它依赖原型链,也意味着它不跨执行上下文:
- 在 iframe 或 Worker 中创建的数组,
arr instanceof Array会返回false(因为两个Array构造函数不是同一个) - 无法检测原始类型:
"abc" instanceof String永远是false - 不能用于内置类型别名,比如
new Map() instanceof Object是true,但你通常并不想这么用
const iframe = document.createElement('iframe');
document.body.appendChild(iframe);
const iframeArray = iframe.contentWindow.Array;
const arr = new iframeArray([1, 2, 3]);
console.log(arr instanceof Array); // false
console.log(Array.isArray(arr)); // true ← 正确姿势
更靠谱的类型检测组合方案
没有银弹,但有共识做法:
- 原始类型优先用
typeof(typeof x === "string"安全) - 区分数组用
Array.isArray(x)(ES5+,跨 iframe 可靠) - 检测内置对象用
Object.prototype.toString.call(x),它返回标准字符串如"[object Date]"、"[object RegExp]" - 自定义类实例可用
instanceof,但确保构造函数作用域一致;或改用x.constructor === MyClass(注意constructor可被篡改)
function typeOf(x) {
if (x === null) return 'null';
if (typeof x === 'object') {
return Object.prototype.toString.call(x).slice(8, -1).toLowerCase();
}
return typeof x;
}
// typeOf([]) → "array", typeOf(/a/) → "regexp", typeOf(null) → "null"
最常被忽略的一点:类型检测不是目的,而是为了后续分支逻辑服务。别堆砌一堆 if (typeof ... && !(x instanceof ...)),先想清楚你要处理的是什么结构,再选最窄、最稳定的检测方式——比如要遍历就用 Array.isArray 或检查 Symbol.iterator,而不是执着于“它到底算不算一个对象”。











