模拟instanceof
2024年3月19日小于 1 分钟
代码
function myInstanceof(instance, constructor) {
if (typeof instance !== 'object') {
return false;
}
const prototype = constructor.prototype;
let tmpPrototype = Object.getPrototypeOf(instance);
while (true) {
if (tmpPrototype === null) {
return false;
}
if (tmpPrototype === prototype) {
return true;
}
tmpPrototype = Object.getPrototypeOf(tmpPrototype);
}
}
测试
const test = []
myInstanceof(test,Array) // true