首先来看几个例子
console.log("111" instanceof Object); //false
console.log({} instanceof Object); //true
console.log([] instanceof Array); //true
console.log(String instanceof String); //false
instanceof 的原理:其实就是判断左边的对象是否在右边对象的原型链上也就是说:left.__proto__ === right.prototype,但是了解过原型链的朋友都知道,原型链的查找是会一层一层去找的,也就是说left.__proto__找不到的话就会去找 left.__proto__.__proto__,直到找到顶层是 null 为止。
function instanceOf(child, parent) {
let left = child;
let right = parent.prototype;
while (true) {
if (left === null) {
return false;
}
if (left === right) {
return true;
}
left = left.__proto__;//找不到往上一层找
}
}
ok,测试一下
console.log(instanceOf({}, Object)); //true
console.log(instanceOf({}, String)); //false
console.log(instanceOf(null, Object)); //false
console.log(instanceOf([], Array)); //true
console.log(instanceOf(String, String)); //false