Search code examples
javascriptprototypeprototype-chain

Only First child can access methods and properties not Descendants in Prototypal inheritance


let animal = {
  eats: true,
  walk() {
    alert("Animal walk");
  }
};

let rabbit = {
  jumps: true,
  __proto__: animal
};

let longEar = {
  earLength: 10,
  __proto__: rabbit
};

// walk is taken from the prototype chain
longEar.walk(); // Animal walk
alert(longEar.jumps); // true (from rabbit)`

In the above example Only Rabbit can access properties and methods of animals because its first child not longEar because its child of rabbit. Suppose we created below example

let horse = {
  jumps: true,
  __proto__: animal
};

let longHoof = {
  hoofLength: 10,
  __proto__: horse
};

In simple words, Whoever inherit first child can only access from animals.

Animals:

  • Horse (must access animals properties and methods) meanwhile longHoof Inherit Horse (should not access properties and methods of Animals)

There is no way i can stop this Is there any special method or trick to prevent it?


Solution

  • As a workaround, you can set the prototype of the top layer to {}. We need to use Object.assign() to get a copy of the rabbit object and not change the original rabbit.

    let animal = {
      eats: true,
      walk() {
        alert("Animal walk");
      }
    };
    
    let rabbit = {
      jumps: true,
      __proto__: animal
    };
    
    let longEar = {
      earLength: 10,
      __proto__: Object.setPrototypeOf(Object.assign({}, rabbit), {})
    };
    
    
    // walk is taken from the prototype chain
    longEar.walk(); // Uncaught TypeError: longEar.walk is not a function
    alert(longEar.jumps); // true (from rabbit)`
    rabbit.walk() // rabbit can still walk