instanceof 的原理

2023-05-03编程技术224719

涉及面试题: instanceof 的原理是什么?

instanceof 可以正确的判断对象的类型,因为内部机制是通过判断对象的原型链中是不是 能找到类型的 prototype

实现一下 instanceof

首先获取类型的原型;
然后获得对象的原型;
然后一直循环判断对象的原型是否等于类型的原型,直到对象原型为 null ,因为原型链 最终为 null 。

function myInstanceof(left, right) {
let prototype = right.prototype
left = left.__proto__
while (true) {
if (left === null || left === undefined){
return false
}
if (prototype === left){
return true
}
left = left.__proto__
}
}

instanceof 的原理的相关教程结束。

本文地址:https://www.ufcn.cn/tutorials/2607334.html

如非特殊说明,本站内容均来自于网友自主分享,概不代表本站观点,如有任何问题我们都将在收到反馈后的第一时间进行处理!