JavaScript Inheritance Pseudo-classical inheritance

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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.

6

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) {
    this.id = id;
    this.name = name;
}

var foo = new Foo(1, 'foo');
console.log(foo.id);

Console output

1

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.

Foo.prototype.bar = 'bar';
console.log(foo.bar);

Console output

bar

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

console.log(foo.constructor);

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);

true

console.log(foo instaceof Object);

true



Got any JavaScript Question?