JavaScript Pseudoclassical Inheritance For Dummies


While learning the pseudoclassical pattern in JavaScript at Hack Reactor, I discovered that there seems to be some confusion about the "best" way to achieve it. This is compounded by changing language standards over the years and the mounds of incorrect or outdated information out on the web.

As you'll see, getting inheritance to work correctly is actually not as daunting as it seems. Let's explore this pattern by implementing some of the utensil family tree:

utensil family tree

Here we go.

    // This is our base Utensil class
var Utensil = function() {  
  // It has a few properties
  this.madeOf = "metal";
  this.purpose = "eating";
  this.isDirty = false;
// And some methods
Utensil.prototype.use = function() {  
  this.isDirty = true;
Utensil.prototype.wash = function() {  
  this.isDirty = false;

// Let's make a spoon, inheriting from Utensil
var Spoon = function() {  
  // We need to inherit Utensil's properties;
  // And define some of Spoon's own
  this.goodFor = "soup";
  this.shape = "concave";
// Now, let's inherit Utensil's methods
Spoon.prototype = Object.create(Utensil.prototype);  
Spoon.prototype.constructor = Spoon;  

That is actually all we need. Let's try a few things.

    var utensil = new Utensil();
var spoon = new Spoon();

// What are Utensils made of?
console.log(utensil.madeOf); // metal

// What about spoons?
console.log(spoon.madeOf); // metal

// What are Spoons good for?
console.log(spoon.goodFor); // soup

// Let's use a spoon
console.log(spoon.isDirty); // true  
console.log(utensil.isDirty); // false  

Sweet, huh? Spoons have inherited properties (being made of metal) from Utensils and can also use their methods (use()).

We can go deeper.

    var Spork = function() {
  // We are going to inherit from Spoon this time;
  // But our spork will be plastic
  this.madeOf = "plastic";
  // And good for anything
  this.goodFor = "everything!";
  // And have its own property
  this.prongs = 3;

// Can't forget about the methods
Spork.prototype = Object.create(Spoon.prototype);  
Spork.prototype.constructor = Spork;  

And, finally, let's test some properties and methods from a few classes:

    var spork = new Spork();
// A Utensil property
console.log(spork.purpose); // eating  
// A Spoon property
console.log(spork.shape); // concave  
// A Spork property
console.log(spork.prongs); // 3  
// A Utensil method
console.log(spork.isDirty); // true  

And there you have it. We can add properties and methods as needed to each class, and they will be inherited as we expect.

Valentyn Boginskey
Valentyn Boginskey

Valentyn is a system administrator turning web developer. He is passionate about privacy and virtual currencies. In his spare time, he enjoys mountain biking, skiing, backpacking, and racing go-karts.