Prototypes in JavaScript

Do you remember the prototype chain?

Prototypes in JavaScript

Here is the summary of JavaScript's prototypes from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain.

  • In JS, there is no implementation of a class per se
    • the ES2015's class keyword is just a syntactical sugar
  • When it comes to inheritance, JS only has one construct: objects.
  • An object has
    • private prototype: a link to another object
    • own properties: other properties
  • An object a's prototype is denoted as a.[[Prototype]]
  • You can access the prototype of an object a (a.k.a. a.[[Prototype]])by
    • Object.getPrototypeOf(a)
    • Object.setPrototypeOf(a)
  • Note that func.prototype is a different beast!
    • It specifies the [[Prototype]] to be assigned to all instances of objects created by the given function when used as a constructor.
const f = function() {
	this.a = 1;
	this.b = 2;
};

const o = new f(); // {a: 1, b: 2}
Initial setting.
Illustration of the initial setting.
f.prototype.b = 3;
f.prototype.c = 4;
This shows that all the instances of f has a link to f.prototype as their [[Prototype]]
Object.getPrototypeOf(Object.getPrototypeOf(o)).d = 5
You can even modify Object.prototype.
Object.setPrototypeOf(Object.getPrototypeOf(o), {e:6})
Object.setPrototypeOf inserts the passed object in the prototype chain.