Prototypes, Inheritances

Prototypal inheritance

[[Prototype]]

let animal = {
  eats: true,
};

let rabbit = {
  jumps: true,
};

rabbit.__proto__ = animal;

console.log(rabbit.eats); // true
console.log(rabbit.jumps); // true

The __proto__ must be an object or null

F.prototype

Used when a object is created by a constructor function, like new F()

let animal = {
  eats: true,
};

function Rabbit(name) {
  this.name = name;
}

Rabbit.prototype = animal;

let rabbit = new Rabbit("White Rabbit"); // When a new Rabbit is created,
// assign its [[Prototype]] to animal

console.log(rabbit.eats); // true
function Rabbit() {}

/* default prototype
Rabbit.prototype = { constructor: Rabbit };
*/

Native prototypes

let obj = {};

console.log(obj.__proto__ === Object.prototype); // true

console.log(obj.toString === obj.__proto__.toString); // true
console.log(obj.toString === Object.prototype.toString); // true

There is no more [[Prototype]] in the chain above Object.prototype

let arr = [1, 2, 3];

console.log(arr.__proto__ === Array.prototype); // true

console.log(arr.__proto__.__proto__ === Object.prototype); // true

console.log(arr.__proto__.__proto__.__proto__); // null

console.log(arr); // 1,2,3 <-- the result of Array.prototype.toString
// show becomes available to all strings
String.prototype.show = function () {
  alert(this);
};

"Boom!".show(); // Boom!
let obj = {
  0: "Hello",
  1: "World!",
  length = 2,
};
obj.join = Array.prototype.join;
console.log(obj.join(',')); // Hello,World!