Javascript Pseudo-Classical Subclassing

Although Javascript does not include support for classes, there are Constructor patterns that allow us to achieve the same outcome. This post will discuss the optimal pattern for instantiating a class AND subclasses.

Pseudo-Classical Instantiation

First, let’s create a class that we will later sub-class:

1
2
3
4
5
6
7
8
9
10
11
function Animal( age, name ) {
this.age = age;
this.name = name;
}
Animal.prototype.toString = function () {
return this.name + " is " + this.age + " years old!";
};
var animal = new Animal(3, 'buddy');
animal.toString(); //"buddy is 3 years old!""

##Pseudo-Classical Subclassing

Now, we need to find a way to subclass the Animal class such that the subclass to Animal’s properties, as well as access to the prototype chain methods.

Here is the optimal way to sub-class and keeping the prototype chain correctly up-to-date

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var Dog = function( age, name ) {
//This is giving Dog access to the Animal properties within the Animal constructor function (but not the prototype methods yet).
Animal.call(this, age, name);
}
//This is pointing Dog's empty prototype object to the Animal prototype object
Dog.prototype = Object.create(Animal.prototype);
//The previous line overwrote Dog's prototype constructor property to Animal. We reset it back to Dog.
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
alert(this.name + ' barks!');
};
var dog = new Dog( 3, 'buddy');