A Quick Explanation of Prototypical Inheritance in JavaScript

The concept of a prototype as employed in JavaScript is simple. If object B is a prototype for object A , then whenever B has a property, such as a color, A will inherit that same color, unless explicitly stated otherwise. So we don’t have to repeat all the information about A that it inherits from B.

A might inherit from B and B in turn from C, etc. This is called a prototype chain. Inheritance works all along the chain. For example, if C specified a color, but neither B nor A did, A would inherit its color from C .

Consider the example above. In this prototype structure, D, E, and F inherit from the prototype P, which in turn inherits from Square. P specifies both a fill (interior color) and stroke (boundary color). In addition D specifies fill, and F, stroke. The three squares which result via the rules of inheritance from this structure are pictured on the far left. For example, the bottom square F inherits its fill from P, but its stroke is set in F itself.

Here is code which would produce the structure:

let P = Object.create(Square);
P.fill = 'red';
P.stroke = 'blue';
let D = Object.create(P);
let E = Object.create(P);
let F = Object.create(P);
D.fill = 'green';
F.stroke = 'magenta';
F.fill === 'red';

The properties which are attached directly to objects (such as F’s stroke), rather than inherited up the prototype chain are called “own properties”.

Note that I have not mentioned the word “class” so far. Prototypical and class inheritance are different schemes. JavaScript does support classes in a limited sense, but only as syntactic sugar which does not affect the underlying structure of objects. Classes were added recently (2015) whereas prototypical inheritance is at the foundation of JavaScript, and has been there all along.