JavaScript Pseudo-classical inheritance


It's an emulation of classical inheritance using prototypical inheritance which shows how powerful prototypes are. It was made to make the language more attractive to programmers coming from other languages.


IMPORTANT NOTE: Since ES6 it doesn't make sense to use pseudo-calssical inheritance since the language simulates conventional classes. If you're not using ES6, you should. If you still want to use the classical inheritance pattern and you're in a ECMAScript 5 or lower environment, then pseudo-classical is your best bet.

A "class" is just a function that is made to be called with the new operand and it's used as a constructor.

function Foo(id, name) { = id; = name;

var foo = new Foo(1, 'foo');

Console output


foo is an instance of Foo.The JavaScript coding convention says if a function begins with a capital letter case it can be called as a constructor (with the new operand).

To add properties or methods to the "class" you have to add them to it's prototype, which can be found in the prototype property of the constructor. = 'bar';

Console output


In fact what Foo is doing as a "constructor" is just creating objects with Foo.prototype as it's prototype.

You can find a reference to its constructor on every object


function Foo(id, name) { ...

console.log({ }.constructor);

function Object() { [native code] }

And also check if an object is an instance of a given class with the instanceof operator

console.log(foo instanceof Foo);


console.log(foo instaceof Object);