- 原型链的本质是链表
- 原型链上的节点是各种原型对象,比如 Fuction.prototype、Object.prototype
- 原型链通过proto属性链接各种原型对象
案例
对象:
obj -> Object.prototype -> null
数组:
arr-> Array.prototype -> Object.prototype -> null
函数:
func -> Function.prototype -> Object.prototype -> null
遍历原型链
实现 instanceOf
思路:如果 A 沿着原型链能够找到 B 的原型对象 B.prototype,那么 A instanceOf B 为 true
function instanceOf(A, B) {
let p = A;
while(p != null) {
if (p === B.prototype) {
return true;
}
p = p.__proto__;
}
return false;
}
console.log(instanceOf('', Object))