Classical inheritance in JavaScript
August 8th, 2010 by JorisO | Filed under Front-end development, JavaScript.JavaScript currently lacks classes in the classical sense, but it can be made to imitate classical class-based inheritance hierarchies with a few simple helper functions.
There’s a lot of different opinions on how JavaScript should be made to imitate classical inheritance patterns. The below is just one method of many.
JavaScript Class
The JavaScript object used to represent a class is basically just a constructor function:
function Animal(name){
this.name = name;
}
//add a method
Animal.prototype.getName = function(){
return this.name
}
//create an instance
var animal = new Animal('Tom');
JavaScript subClass
To now allow a new class to subClass our new JavaScript class we need something that performs similar task to the ‘extends’ functionality in languages as Java and PHP.
We can define a JavaScript ‘extends’ function as follows:
function extends(childClass, parentClass){
var O = function(){}; //create new object to contain parentClass prototype without instantiating parentClass.
O.prototype = parentClass.prototype
childClass.prototype = new O(); //setup prototype chain
childClass.prototype.constructor = childClass; //reset constructor to childClass
childClass.parentClass = parentClass.prototype; //provide parentClass attribute for childClass constructor functions
if(parentClass.prototype.constructor == Object.prototype.constructor){
parentClass.prototype.constructor = parentClass;
}
}
Now to create a subclass of Animal :
function Sloth(name,bananas){
Sloth.parentClass.constructor.call(this,name);
this.bananas = bananas;
}
extend(Sloth,Animal);
Sloth.prototype.getBananas = function(){
return this.bananas;
}
Now if we’d want to override yet incorporate a parents method in the childClass we could do :
Sloth.getName = function (){
var name = Sloth.parentClass.getName.call(this);
return name + ' was provided by overridden method';
}
Tags: JavaScript, OOP