当前位置: 首页 > news >正文

`typeof` 和 `instanceof` 的核心实现原理

1. typeof 的核心实现原理

JavaScript 内部的类型标签机制

在 JavaScript 引擎内部,每个值都有一个类型标签(type tag)存储在值的低位数位中。

// 模拟 typeof 的底层实现逻辑
function myTypeof(value) {// 1. 处理 null 的特殊情况if (value === null) {return 'object';}// 2. 处理函数的特殊情况if (typeof value === 'function') {return 'function';}// 3. 基于值的内部 [[Class]] 属性判断const type = Object.prototype.toString.call(value).slice(8, -1).toLowerCase();// 4. 特殊处理:document.all 在旧浏览器中返回 'undefined'if (value === undefined) {return 'undefined';}// 5. 基本类型映射const typeMap = {number: 'number',string: 'string',boolean: 'boolean',symbol: 'symbol',bigint: 'bigint',object: 'object'};return typeMap[type] || 'object';
}

实际引擎中的实现(简化版)

// V8 引擎中的简化实现逻辑
function V8Typeof(obj) {// 检查值的内部表示const type = %_ClassOf(obj);switch (type) {case 'Number': return 'number';case 'String': return 'string';case 'Boolean': return 'boolean';case 'Symbol': return 'symbol';case 'BigInt': return 'bigint';case 'Function': return 'function';case 'Undefined': return 'undefined';case 'Null': return 'object'; // 历史遗留问题default: return 'object';}
}

typeof 的特殊行为解释

// 历史遗留的 bug
typeof null === 'object' // true// 函数特殊处理
typeof function() {} === 'function' // true
typeof class {} === 'function'      // true// 其他对象
typeof [] === 'object'              // true
typeof {} === 'object'              // true
typeof new Date() === 'object'      // true

2. instanceof 的核心实现原理

instanceof 的底层实现

// instanceof 的 polyfill 实现
function myInstanceof(instance, constructor) {// 1. 基本类型直接返回 falseif (instance === null || typeof instance !== 'object' && typeof instance !== 'function') {return false;}// 2. 获取实例的原型let proto = Object.getPrototypeOf(instance);// 3. 沿着原型链向上查找while (proto !== null) {// 4. 如果找到构造函数的 prototype,返回 trueif (proto === constructor.prototype) {return true;}// 5. 继续向上查找proto = Object.getPrototypeOf(proto);}// 6. 原型链尽头未找到,返回 falsereturn false;
}

更完整的实现(包含边界情况)

function completeInstanceof(instance, constructor) {// 检查 constructor 是否有效if (typeof constructor !== 'function') {throw new TypeError('Right-hand side of instanceof is not callable');}// 检查 instance 是否为对象(除 null 外)if (instance === null || (typeof instance !== 'object' && typeof instance !== 'function')) {return false;}// 获取构造函数的原型const constructorProto = constructor.prototype;// 如果构造函数的原型不是对象,抛出错误if (typeof constructorProto !== 'object' && constructorProto !== null) {throw new TypeError('Function has non-object prototype in instanceof check');}// 遍历原型链let currentProto = Object.getPrototypeOf(instance);while (currentProto !== null) {if (currentProto === constructorProto) {return true;}currentProto = Object.getPrototypeOf(currentProto);}return false;
}

3. 实际应用示例

typeof 应用场景

function typeCheck(value) {const type = typeof value;switch (type) {case 'string':return `字符串: ${value}`;case 'number':return `数字: ${value}`;case 'boolean':return `布尔值: ${value}`;case 'undefined':return '未定义';case 'function':return '函数';default:if (value === null) return 'null';return `对象: ${value.constructor.name}`;}
}console.log(typeCheck('hello'));    // 字符串: hello
console.log(typeCheck(42));         // 数字: 42
console.log(typeCheck(null));       // null

instanceof 应用场景

class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}const dog = new Dog();
const cat = new Cat();console.log(myInstanceof(dog, Dog));     // true
console.log(myInstanceof(dog, Animal));  // true
console.log(myInstanceof(dog, Cat));     // false
console.log(myInstanceof([], Array));    // true
console.log(myInstanceof([], Object));   // true

4. 性能优化版本

优化的 instanceof(使用缓存)

function optimizedInstanceof() {const cache = new WeakMap();return function(instance, constructor) {// 基本类型快速返回if (instance === null || typeof instance !== 'object') {return false;}// 检查缓存const key = `${constructor.name}-${typeof instance}`;if (cache.has(key)) {return cache.get(key);}// 原型链查找let proto = Object.getPrototypeOf(instance);while (proto !== null) {if (proto === constructor.prototype) {cache.set(key, true);return true;}proto = Object.getPrototypeOf(proto);}cache.set(key, false);return false;};
}const fastInstanceof = optimizedInstanceof();

5. 核心区别总结

特性 typeof instanceof
检查目标 值的类型 原型链关系
返回值 字符串 布尔值
处理null 返回'object' 返回false
性能 O(1) O(n) - 原型链长度
适用场景 基本类型检查 继承关系检查

实际使用建议

// typeof 适合检查基本类型
if (typeof variable === 'string') {// 处理字符串
}// instanceof 适合检查对象类型和继承关系
if (variable instanceof Error) {// 处理错误对象
}// 对于数组,推荐使用 Array.isArray
if (Array.isArray(variable)) {// 处理数组
}
http://www.jsqmd.com/news/43478/

相关文章:

  • 2025年国标隔热条品牌综合实力排行榜TOP10推荐
  • linux 5 下载
  • 2025年热门的无锡写字楼绿植租赁厂家最新推荐排行榜
  • 使用Docker Compose工具进行容器编排
  • 2025年口碑好的园区目视化规划最新用户口碑榜平台
  • 详细介绍:上下文工程实践:利用GLM-4.6和TRAE SOLO打造新粗野主义风格音乐创作网站
  • 写论文的秘密神器
  • 信创背景下“稳”与“敏”共生:大型国企智能 ITSM 平台选型指南与实践参考
  • 2025年口碑好的悉尼澳洲海外仓中转配送品牌推荐榜
  • 2025年靠谱的车载灭火器装置厂家推荐及选择参考
  • 2025年质量好的幼儿园特教设备高评价厂家推荐榜
  • 2025年口碑好的设计师三段力缓冲铰链厂家最新热销排行
  • 2025年5d全息投影宴会厅供货厂家权威推荐榜单:3d全息宴会厅/全息投影宴会厅/5D全息宴会厅源头厂家精选
  • 2025年质量好的光通信检测仪器厂家最新TOP实力排行
  • 2025年靠谱的防爆热电偶厂家最新TOP排行榜
  • 洛谷题单指南-组合数学与计数-P5520 [yLOI2019] 青原樱
  • 2025年评价高的长毛绒滤袋厂家实力及用户口碑排行榜
  • 2025年质量好的旋喷钻机用户好评厂家排行
  • 2025年比较好的新疆特级棉被厂家最新权威实力榜
  • 2025年全封闭工地洗轮机厂家权威推荐榜单:封闭式冲洗台/全封闭洗车台/封闭型洗轮机源头厂家精选
  • 2025年评价高的直流固态继电器TOP品牌厂家排行榜
  • 2025年热门的耐化学介质氢化丁腈橡胶行业内口碑厂家排行榜
  • 2025年热门的岳山红油豆瓣酱最新TOP厂家排名
  • 2025年口碑好的冷拉型钢光圆厂家最新推荐权威榜
  • 2025年口碑好的冷拉异型钢光圆厂家推荐及选购指南
  • 2025年苗木批发基地十大口碑批发商权威排行,樱花/白蜡/紫薇/无刺枸骨球/红叶石楠/金森女贞/金叶女贞/青叶复叶槭/金叶复叶槭供应商排行榜
  • matplotlib plot 折线图使用体验
  • 2025年苗木批发基地批发商口碑排行,丝棉木/国槐/油松/栾树/红叶李/青叶复叶槭/樱花/金叶女贞/金叶复叶槭/无刺枸骨球种植推荐榜单
  • 2025年比较好的环网柜机构行程防水微动开关行业内知名厂家排行榜
  • 最新苗木批发基地排行榜出炉,2025年这些基地最受欢迎,樱花/丝棉木/红叶李/金森女贞/紫薇/苗木/青叶复叶槭/油松供应商推荐排行榜单