Introduction
Javascript is a very powerful language. It looks simple, but it becomes very messy if you don't know what you're doing. Inheritance in Javascript is the perfect example of it.
Background
I've been looking over the internet for days for the best implementation of inheritance. Let's face the most common answers are very complex. There is a very simple method with modern browsers if you understand these three keywords:
__proto__ prototype constutructor
The core mechanism of inheritance: __proto__
Every object in JS has the hidden property __proto__. When you use one property that is not defined in the object, JS automatically tries to find the property in the object in __proto__:
var o = {};
o.toString();
In this example, it's obvious that the function toString is not declared in the o object. JS will look in the __proto__ of o to find this function and eventually JS will use: o.__proto__.toString()
This is the mechanism you have to use to inherit one object to an other.
var Mammal = {
legs: 4
};
var Cat = {
fur: true
};
Cat.__proto__ = Mammal;
Cat.legs will be translated into Cat.__proto__.legs at runtime.
A class is not an object!
There a real difference between objects and classes that people tends to forget in JS. Classes are not objects.
Classes describe objects like templates. Objects are instances of classes.
The class template: prototype
In JS you create classes using functions - this may be a little odd at the beginning.
var Mammal = function () { }; When using functions as classes you use another hidden properties: prototype. This is where most of the misunderstanding takes place: prototype and __proto__ are not the same thing! prototype describe what properties will be inherited when the object will be created (with the new mechanism)
In JS when you do:
var m = new Mammal();
This is what JS real do:
var m = {};
m.__proto__ = Mammal.prototype;
Mammal.call(m); Thus every properties in Mammal.prototype will be accessible in m.
Let's create our Cat class.
var Cat = function () { }; And now, for the inheritance:
Cat.prototype.__proto__ = Mammal.prototype;
And that's it ! Now when you create a new Cat it's __proto__ will be Cat.prototype and it's __proto__.__proto__ will be Mammal.prototype so your new born kitten will have access to the Cat and Mammal properties.
Static properties
It's really easy to add static properties to your class. Instead of setting your property into the prototype you just set it in the class itself:
Mammal.legs = 4;
The problem is that Cat cannot access the legs property. So we have to have another inheritance:
Cat.__proto__ = Mammal;
And once again you don't have to add anything more.
The contructor property
I wasn't totally correct when I explained what new does in JS. I've forgotten one line:
var m = {};
m.__proto__ = Mammal.prototype;
m.constructor = Mammal; m.constructor.call(m);
That means the hidden property constructor holds the class. That is useful to reach static properties.
m.constructor.legs
The construction chain
When you create a new Cat you have to explicitly call the parent constructor. This can be achieved with __proto__ and constructor:
var c = new Cat();
c.__proto__; c.__proto__.__proto__; c.__proto__.__proto__.constructor; c.__proto__.__proto__.constructor.call(c);
All together
In order to simplify the inheritance process here's a very helpful yet simple function:
Function.prototype.subClass = function(superClass) {
this.prototype.__proto__ = superClass.prototype; this.__proto__ = superClass;
this.prototype.superClass = superClass; } The two first lines provide inheritance for properties and static properties.
The superClass property is a shortcut to the super/parent class - useful to call super/parent function such constructor.
var Mammal = function () { ... }
var Cat = function () {
this.superClass(); }
Cat.subClass(Mammal); Enhanced version: the toClass function
Here's an enhanced version that simplifies dramatically the class creation process in JS.
Function.prototype.toClass = function (superClass, members) {
if (members == undefined) {
members = superClass;
superClass = null;
}
if (superClass) {
this.prototype.__proto__ =
superClass.constructor == Object ?
superClass : superClass.prototype;
this.__proto__ = superClass;
this.prototype.superClass = superClass; this.prototype.static = this; }
for(var k in members) {
this.prototype[k] = members[k];
}
return this;
};
When using this function, it creates a static property that is an exact synonym of constructor, but it enhance the readability when reaching for static properties.
Here's an example of how to use this function:
Animal = function (){
}
Animal.type = "Animal";
Animal.ShowType = function () {
console.log(this.type);
}
Animal.toClass({
talk: function() {
console.log(this.sound+"!");
}
});
Dog = function (){
this.superClass();
}
Dog.type = "Dog";
Dog.toClass(Animal, {
sound: "bark",
});
Cat = function (){
this.superClass();
}
Cat.toClass(Animal, {
sound: "meow",
});
a = new Animal ();
a.talk();
d = new Dog ();
d.talk();
c = new Cat ();
c.talk();
Animal.ShowType(); Dog.ShowType(); c.static.type; Points of Interest
Since __proto__ is not exposed in IE, this doesn't work at all with Microsoft browser.
You'll have similar problem with Safari < 5 and Opera < 10.50
History
2012-09-29 First publication
2012-10-02 Added list of non working browser
2012-10-04 Minor changes and typo corrections
Florent has been learning code since he was 8. Basic, then C, C++, ASM (z80, x86, ARM), Java, PHP, SQL, and finally JS - his last love.
Florent has worked in the video game industry and became an entrepreneur by co-found several projects such as eCommerce, online community and lastly one of the most important dating website in France.