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?
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.