Categories
Javascript

Prototype methods, objects without proto

The __proto__ is considered outdated and somewhat deprecated (in browser-only part of the JavaScript standard).
The modern methods are:

Object.create(proto, descriptors) – creates an empty object
Object.getPrototypeOf(obj) – returns the Prototype of obj.
Object.setPrototypeOf(obj, proto) – sets the Prototype of obj to proto.

let animal = {
  eats: true
};

// create a new object with animal as a prototype
let rabbit = Object.create(animal);

alert(rabbit.eats); // true

alert(Object.getPrototypeOf(rabbit) === animal); // true

Object.setPrototypeOf(rabbit, {}); // change the prototype of rabbit to {}
function Rabbit(name) {
  this.name = name;
}
Rabbit.prototype.sayHi = function() {
  alert(this.name);
};

let rabbit = new Rabbit("Rabbit")

rabbit.sayHi(); // "Rabbit"
Rabbit.prototype.sayHi(); //undefined
Object.getPrototypeOf(rabbit).sayHi(); //undefined
rabbit.__proto__.sayHi(); //undefined

Categories
Javascript

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)