面试时被问到了,虽然思路说了出来,但写的时候还是磕磕巴巴的,让面试官提醒了才写出来,太丢人了┭┮﹏┭┮
思路
instanceof 运算符用于判断构造函数的 prototype 属性是否出现在对象的原型链中的任何位置。
实现步骤:
- 获得对象的原型
- 获得构造函数的prototype
- 循环判断对象的原型是否等于构造函数的prototype,如果不等于,则根据原型链往下找,直到对象原型为null
function _instanceof(left, right) {
let letfProto = left.__proto__
let rightPrototype = right.prototype
// 当letfProto不为null时,则一直循环遍历直到找到构造函数的 prototype属性
while (letfProto) {
if (letfProto === rightPrototype) {
return true
}
letfProto = letfProto.__proto__
}
return false
}
console.log(_instanceof([], Array)); // true
console.log(_instanceof([], Object)); // true
console.log([] instanceof Array); // true
console.log([] instanceof Object); // true