简介
- 原型链的本质就是链表
- 原型链上的节点是各种原型对象,比如Function.prototype、Object.prototype ......
- 原型链是通过__protto__属性连接各种原型对象,而链表是通过next属性连接下一个对象
原型链长什么样
- obj -> Object.prototype -> null
- func -> Function.prototype -> Object.prototype -> null
- arr -> Array.prototype -> Object.prototype -> null
instance 原理
利用原型链遍历查找
const instanceOf = (A, B) => {
let p = A;
while(p) {
if (p == B.prototype) {
return true;
}
p = p.__proto__;
}
return false;
}
console.log(instanceOf({}, Object));
console.log(instanceOf([], Object));