• 原型链的本质是链表
  • 原型链上的节点是各种原型对象,比如 Fuction.prototype、Object.prototype
  • 原型链通过proto属性链接各种原型对象

案例

对象:
obj -> Object.prototype -> null
image.png

数组:
arr-> Array.prototype -> Object.prototype -> null

函数:
func -> Function.prototype -> Object.prototype -> null

遍历原型链

image.png

实现 instanceOf

思路:如果 A 沿着原型链能够找到 B 的原型对象 B.prototype,那么 A instanceOf B 为 true

  1. function instanceOf(A, B) {
  2. let p = A;
  3. while(p != null) {
  4. if (p === B.prototype) {
  5. return true;
  6. }
  7. p = p.__proto__;
  8. }
  9. return false;
  10. }
  11. console.log(instanceOf('', Object))