typeof判断基础类型(含function、symbol),instanceof判断引用类型是否由某构造函数创建;二者解决不同层面问题,混用易致误判。

typeof 和 instanceof 解决的是不同层面的问题:前者判断基础类型(含 function 和 symbol),后者判断引用类型是否由某个构造函数创建。混用或只依赖其中一个,很容易掉进类型误判的坑里。
typeof 只能识别基础类型,对大部分对象都返回 "object"
typeof 在 JavaScript 中是操作符,不是函数,它对原始值(string、number、boolean、undefined、symbol、bigint)和 function 能准确返回字符串标识,但对所有对象(包括数组、正则、日期、null)一律返回 "object"。
常见误判场景:
-
typeof null === "object"—— 这是历史 bug,至今未修复 -
typeof [] === "object",typeof new Date() === "object",无法区分具体构造来源 -
typeof async function(){} === "function",但typeof Promise.resolve() === "object"
所以别用 typeof 判断数组或正则——它帮不上忙。
立即学习“Java免费学习笔记(深入)”;
instanceof 用于检测对象是否由某构造函数“实例化”而来
instanceof 检查的是对象的原型链上是否存在指定构造函数的 prototype。它只适用于引用类型,对原始值(如 "abc"、42)始终返回 false。
典型使用方式:
const arr = [1, 2, 3];
arr instanceof Array; // true
arr instanceof Object; // true(因为 Array.prototype.__proto__ === Object.prototype)
const re = /test/;
re instanceof RegExp; // true
const str = "hello";
str instanceof String; // false(这是原始字符串,不是 String 实例)
new String("hello") instanceof String; // true
注意点:
- 跨 iframe 或跨上下文时,
instanceof会失效(比如 iframe 里的[] instanceof Array在父页面为false,因构造函数不共享) - 不能用于检测原始类型,也不适合判断
null或undefined - ES6 class 也支持:
class A {}; new A() instanceof A === true
实际项目中怎么安全判断变量类型?
单靠 typeof 或 instanceof 都不够。推荐组合策略:
- 先用
typeof快速分流原始类型:typeof x === "string"、typeof x === "function" - 对
"object"类型,再用Object.prototype.toString.call(x)获取精确标签 - 需要确认是否为某类实例且环境可控(同上下文),才用
instanceof
例如判断数组:
function isArray(x) {
return Array.isArray(x); // 最优解,ES5+ 原生支持
}
// 或退化写法(兼容极老环境):
function isArray(x) {
return Object.prototype.toString.call(x) === "[object Array]";
}
判断 Promise:
function isPromise(x) {
return x !== null && typeof x === "object" && typeof x.then === "function";
}
// 注意:不能用 instanceof Promise,因可能跨 realm;也不能只靠 typeof,因普通对象也可能有 then 方法
真正容易被忽略的是:类型判断逻辑一旦进入工具函数或公共库,就必须考虑跨环境、可序列化、不可篡改原型等边界情况。Object.prototype.toString.call() 是目前最稳定可靠的“类型签名”获取方式,比任何单一操作符都更值得依赖。











