Javascript prototype

In JavaScript, objects have a special hidden property Prototype , that is either null or references another object. That object is called “a prototype”:
The property Prototype is internal and hidden, but there are many ways to set it.

let animal = {
  eats: true
};
let cat= {
  jumps: true
};

cat.__proto__ = animal;  // Here sets animal to be a prototype of cat
alert( cat.eats ); // true (**)
alert( cat.jumps ); // true
let animal = {
  eats: true,
  walk() {
    alert("Animal walk");
  }
};

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

// walk is taken from the prototype
rabbit.walk(); // Animal walk

……………………………………………………………………………………………………………

The prototype chain

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)
let animal = {
  jumps: null
};
let rabbit = {
  __proto__: animal,
  jumps: true
};

alert( rabbit.jumps ); // ? (1)

delete rabbit.jumps;

alert( rabbit.jumps ); // ? (2)

delete animal.jumps;

alert( rabbit.jumps ); // ? (3)

5,376 Replies to “Javascript prototype”