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
typeof,一律返回 "object"
instanceof 的原理和致命限制instanceof 的行为等价于:沿着左操作数的 __proto__ 链向上查找,看能否找到右操作数的 prototype 对象。
这意味着它依赖原型链,也意味着它不跨执行上下文:
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,而不是执着于“它到底算不算一个对象”。