1. The prototype chain

The essence of a prototype chain is a linked list

The nodes on the prototype chain are various prototype objects, such as function. prototype, object. prototype…

The prototype chain connects various prototype objects through the __proto__ property

Prototype chain

obj->Object.prototype->null

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

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

The interview questions

  1. A instanceof B is true if A can find b. prototype along the prototype chain
 const instanceof = (A, B) = > {
     let p = A;
     while(p) {
         if(p === B.prototype){
             return true;
         }
         p = p.__proto__;
     }
     return false;
 }
Copy the code
  1. If no x property is found on the A object, the x property is searched along the stereotype chain
   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
Copy the code

2. Obtain the value of the JSON node

const json = {
    a: { b: { c: 1}},d: { e: { f: { h: 2 }, g: { i: 3}}}}// Traverses the path of the JSON object
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
Copy the code