Skip to content

prototypes

Jorge Estanislao Barsoba edited this page Oct 15, 2021 · 1 revision

Must-Knows - JavaScript - Prototypes

Mechanism by which objects in JavaScript inherit features from one another. That's why JavaScript is described as a prototype-based laguage.

The object and its prototype are connected through the __proto__ property.

All objects in JavaScript are instances of Object (except when deliberately prevented).

Object

  • One of the JavaScript's data types
  • Stores keyed collections

Prototype chain

  • An object's prototype object may also have a prototype object, which it inherits features from, and so on
  • Changes to Object.prototype are seen by all objects (except when the properties or methods are overriden)
  • Methods and properties are accessed by walking up the chain

Example: Walking up the prototype chain

Constructor function def:

function Person(first, last) {
    this.name = {
        'first': first,
        'last': last
    };
}

Instance creation:

let person1 = new Person('Bob', 'Smith');

person1 Inherits from prototype > Person Inherits from prototype > Object

If we call person.valueOf():

  • The engine checks if person1 has a valueOf method
  • As it does not, it checks if Person has it
  • As it does not, it checks if Object has it, and as it does, the method is called!

The prototype property is basically a bucket for storing properties and methods that we want to be inherited by objects further down the prototype chain

Sources

Clone this wiki locally