1. instanceof的用法
instanceof运算符用于检测构造函数的prototype属性是否出现在某个实例对象的原型链上。
function Person() {}
function Person2() {}
const usr = new Person();
console.log(usr instanceof Person); // true
console.log(usr instanceof Object); // true
console.log(usr instanceof Person2); // false
如上代码,定义了两个构造函数,Person和Person2,又实用new操作创建了一个Person的实例对象usr。
实用instanceof操作符,分别检验构造函数的prototype属性是否在usr这个实例的原型链上。
当然,结果显示,Person和Object的prototype属性在usr的原型链上。usr不是Person2的实例,故Person2的prototype属性不在usr的原型链上。
2. 实现instanceof
明白了instanceof的功能和原理后,可以自己实现一个instanceof同样功能的函数:
function myInstanceof(obj, constructor) {
// obj的隐式原型
let implicitPrototype = obj?.__proto__;
// 构造函数的原型
const displayPrototype = constructor.prototype;
// 遍历原型链
while (implicitPrototype) {
// 找到,返回true
if (implicitPrototype === displayPrototype) return true;
implicitPrototype = implicitPrototype.__proto__;
}
// 遍历结束还没找到,返回false
return false;
}
myInstanceof函数接收两个参数:实例对象obj和构造函数constructor。
首先拿到实例对象的隐式原型:obj.__proto__,构造函数的原型对象constructor.prototype。
接着,就可以通过不断得到上一级的隐式原型:
implicitPrototype = implicitPrototype.__proto__;
来遍历原型链,寻找displayPrototype是否在原型链上,若找到,返回true。
当implicitPrototype为null时,结束寻找,没有找到,返回false。
原型链其实就是一个类似链表的数据结构。
instanceof做的事,就是在链表上寻找有没有目标节点。从表头节点开始,不断向后遍历,若找到目标节点,返回true。遍历结束还没找到,返回false。
3. 验证
写一个简单的实例验证一下自己实现的instanceof:
function Person() {}
function Person2() {}
const usr = new Person();
function myInstanceof(obj, constructor) {
let implicitPrototype = obj?.__proto__;
const displayPrototype = constructor.prototype;
while (implicitPrototype) {
if (implicitPrototype === displayPrototype) return true;
implicitPrototype = implicitPrototype.__proto__;
}
return false;
}
myInstanceof(usr, Person); // true
myInstanceof(usr, Object); // true
myInstanceof(usr, Person2); // false
myInstanceof(usr, Function); // false
myInstanceof(usr.__proto__, Person); // false
usr.__proto__ instanceof Person; // false
可以看到,myInstanceof正确得出了结果。
有趣的是,usr.__proto__ instanceof Person返回false,说明obj instanceof constructor检测的原型链,不包括obj节点本身。
JavaScript常见手写代码:
「GitHub—code-js」
到此这篇关于JavaScript 手动实现instanceof的文章就介绍到这了,更多相关JavaScript instanceof内容请搜索NICE源码以前的文章或继续浏览下面的相关文章希望大家以后多多支持NICE源码!
