前端与链表 —— 原型链

324 阅读1分钟

1. 原型链

原型链的本质是链表

原型链上的节点是各种原型对象,比如:Function.prototypeObject.prototype……

原型链通过__proto__属性连接各种原型对象

原型链

obj->Object.prototype->null

func->Function.prototype->Object.prototype->null

arr->Array.prototype->Object.prototype->null

面试题

  1. 如果A沿着原型链能找到B.prototype,那么A instanceof B为true
 const instanceof = (A, B) => {
     let p = A;
     while(p) {
         if(p === B.prototype){
             return true;
         }
         p = p.__proto__;
     }
     return false;
 }
  1. 如果在A对象上没有找到x属性,那么会沿着原型链找x属性
   const obj = {};
   Object.prototype.x = 'x';
   const func = () => {};
   Function.prototype.y = 'y';
   console.log(func.x);  //x
   console.log(func.y);  //y
   console.log(obj.x);   //x
   console.log(obj.y);   //undefined

2. 获取JSON的节点值

const json = {
    a: { b: { c: 1 } },
    d: { e: { f: { h: 2 }, g: { i: 3 } } }
}

// 遍历json对象的路径
const path1 = ['a', 'b', 'c'];
const path2 = ['d', 'e', 'f', 'h'];
const path3 = ['d', 'e', 'g', 'i'];

function getPoint(path) {
    let p = json;
    path.forEach(k => {
        p = p[k];
    });
    console.log(p);
}

getPoint(path1); // 1
getPoint(path2); // 2
getPoint(path3); // 3