JavaScript中instanceof运算符原理与模拟实现详解
作者:异步漫步时间:2026-10-25 12:51:59浏览:565
本文详解JavaScript中instanceof运算符的用法与底层原理。通过普通用法、继承判断及复杂对象检测等实例,解析constructor.prototype在原型链中的查找机制,并提供基于__proto__的模拟函数实现代码,帮助深入理解对象类型检测逻辑。
概述
instanceof运算符用于检测一个构造函数的prototype属性所指向的对象,是否存在于另一个待检测对象的原型链上。
语法
obj instanceof Object;//true 实例obj在不在Object构造函数中描述
instanceof运算符的作用是检测constructor.prototype是否存在于参数object的原型链上。
实例
1.instanceof的普通的用法,obj instanceof Object 检测Object.prototype是否存在于参数obj的原型链上。
Person的原型在p的原型链中
function Person(){};
var p =new Person();
console.log(p instanceof Person);//true2.继承中判断实例是否属于它的父类
Student和Person都在s的原型链中
function Person(){};
function Student(){};
var p =new Person();
Student.prototype=p;//继承原型
var s=new Student();
console.log(s instanceof Student);//true
console.log(s instanceof Person);//true3.复杂用法
这里的案例要有熟练的原型链的认识才能理解
function Person() {}
console.log(Object instanceof Object); //true
//第一个Object的原型链:Object=>
//Object.__proto__ => Function.prototype=>Function.prototype.__proto__=>Object.prototype
//第二个Object的原型:Object=> Object.prototype
console.log(Function instanceof Function); //true
//第一个Function的原型链:Function=>Function.__proto__ => Function.prototype
//第二个Function的原型:Function=>Function.prototype
console.log(Function instanceof Object); //true
//Function=>
//Function.__proto__=>Function.prototype=>Function.prototype.__proto__=>Object.prototype
//Object => Object.prototype
console.log(Person instanceof Function); //true
//Person=>Person.__proto__=>Function.prototype
//Function=>Function.prototype
console.log(String instanceof String); //false
//第一个String的原型链:String=>
//String.__proto__=>Function.prototype=>Function.prototype.__proto__=>Object.prototype
//第二个String的原型链:String=>String.prototype
console.log(Boolean instanceof Boolean); //false
//第一个Boolean的原型链:Boolean=>
//Boolean.__proto__=>Function.prototype=>Function.prototype.__proto__=>Object.prototype
//第二个Boolean的原型链:Boolean=>Boolean.prototype
console.log(Person instanceof Person); //false
//第一个Person的原型链:Person=>
//Person.__proto__=>Function.prototype=>Function.prototype.__proto__=>Object.prototype
//第二个Person的原型链:Person=>Person.prototype总结
对应上述规范做个函数模拟A instanceof B:
function _instanceof(A, B) {
var O = B.prototype;// 取B的显示原型
A = A.__proto__;// 取A的隐式原型
while (true) {
//Object.prototype.__proto__ === null
if (A === null)
return false;
if (O === A)// 这里重点:当 O 严格等于 A 时,返回 true
return true;
A = A.__proto__;
}
}到此这篇关于javascript中instanceof运算符的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持本站。
作者最新文章
D3.js 比例尺与坐标轴的配置详解
2026-11-05 16:54:46
JavaScript怎么遍历对象的Symbol键和不可枚举属性
2026-11-05 13:13:39
封装一个健壮的JS字符串判空工具函数
2026-11-05 12:16:14
JavaScript合并数组的三种常用方法:concat、扩展运算符与push
2026-11-05 11:22:29
JavaScript立即执行函数(IIFE)是什么及基本语法
2026-11-05 10:51:19
