🚀 typeof和instanceof操作符的用法和区别

📅 发布于 2026年1月 | 👤 作者:博主 | 🏷️ 标签:typeof, instanceof, 类型检测, JavaScript, Web开发, 前端, 面试

欢迎来到我的博客文章!所有文章都是满满的前端干货,文章简明扼要。

typeof 和 instanceof 是 JavaScript 中用于类型检测的两个核心操作符,typeof:检测基本数据类型,instanceof:检测对象的构造函数/原型链

最佳实践总结

通用、准确的类型判断,推荐方法:Object.prototype.toString.call(obj).slice(8, -1)。

一、typeof:检测基本数据类型

✅ 作用

返回一个字符串,表示操作数的数据类型。

✅ 返回值对照表

表达式 typeof 结果 说明
undefined "undefined" 未定义
null "object" ⚠️ 历史 bug(JS 设计错误)
true / false "boolean" 布尔值
42, 3.14 "number" 数字
123n "bigint" ES2020 新增
"hello" "string" 字符串
Symbol() "symbol" ES6 新增
function f(){} "function" 函数(特殊对象)
{}, [], new Date() "object" 所有对象(包括数组、日期等)

二、instanceof:检测对象的构造函数/原型链

✅ 作用

判断一个对象是否是某个构造函数的实例。通过检查原型链(__proto__)是否包含构造函数的 prototype。

🔍 语法
object instanceof Constructor

✅ 示例

[] instanceof Array; // true
new Date() instanceof Date; // true
/abc/ instanceof RegExp; // true

// 自定义类
class User {}
const user = new User();
user instanceof User; // true

// 继承关系
class Admin extends User {}
const admin = new Admin();
admin instanceof Admin; // true
admin instanceof User; // true(原型链继承)

四、如何正确检测类型?(最佳实践)

✅ 1. 检测原始类型 → 用 typeof

if (typeof value === 'string') { ... }
if (typeof value === 'number') { ... }

✅ 2. 检测具体对象类型 → 用 instanceof(同窗口内)

if (arr instanceof Array) { ... }
if (date instanceof Date) { ... }

六、总结

场景 推荐方法
判断 string / number / boolean / function typeof
判断 null 直接 === null
判断 Array Array.isArray()
判断 Date / RegExp / 自定义类 instanceof(同窗口)
跨 iframe 类型检测 使用 Object.prototype.toString.call()(终极方案)
← 返回首页