How to inherit classes in javascript
First of all, since I made the front page of Ajaxian, a lot of new readers joined in. Welcome to all of you. I would also take a moment to explain that Javascript Kata is a technical blog about javascript and though I will talk here and there about ajax, it is not focused on that subject. It is more about the good javascript techniques that should come along with all the ajax you have to do. I update this site 2 or 3 times a week. Keep reading!
There are hundreds of ways to do inheritance in javascript but a single one is simpler, cleanier and prettier than all the other ones.
Note!
Before reading this article, you should take a look at How to create objects in object-oriented javascript.
A one-liner
To inherit a class in javascript, it’s a one-liner
-
TheSubClass.prototype = new TheParentClass();
As simple as that!
Where to write the one-liner
The problem with that one-liner is where should it goes? Once again, the answer is simple : after the constructor of the sub-class. It may look strange but it is extremely effective.
-
/* The constructor of the Mammal class */
-
function Mammal() {
-
}
-
-
/* The constructor of the Cat class */
-
function Cat() {
-
}
-
// The magic that inherits Cat from Mammal is here!!!!!
-
Cat.prototype = new Mammal();
Is this true inheritance?
In the hundreds of other ways of inheriting classes in javascript, I think that this is the only one that is a true inheritance. What do I mean by true inheritance? I mean that javascript recognizes it as a sub-class of the class. Check this out!
-
/* Above code goes here */
-
-
// Create a cat
-
var theCat = new Cat();
-
-
// Check if the cat is an instance of the Cat class
-
if (theCat instanceof Cat) {
-
alert("theCat is an instance of the Cat class");
-
}
-
-
// Check if the cat is an instance of the Mammal class
-
if (theCat instanceof Mammal) {
-
alert("theCat is an instance of the Mammal class");
-
}
If you execute this code, you’ll see that the cat is an instance of the Cat class and the Mammal class.


A couple questions about this:
1) If you later add a new method to the Mammal prototype, will the Cat prototype also get it?
2) Any tips on explicitly calling the super-class implementation of a function? For instance if Mammal and Cat both had the function Run(), and you wanted to Cat implementation to do some stuff and then call the Mammal implentation.
Thanks, love the site!
BKR
@Brian
First, you can add a method later to the Mammal class that will be available to the Cat class. Beware! You must add it to the prototype :
Mammal.prototype.newMethod = function() { alert(”The new method”); }
Second, as I was writing the example this morning, I was asking myself the same question. Basically, you can’t do it. The new function from the Cat class will simply overwrite the one from the Mammal class. But I’m sure there’s a clean way of doing it. Maybe it will be the subject of my next article
Thanks for loving the site!
I know Dojo had some way of calling a base class function. However, they had a custom function for doing inheritance (dojo.extend() ??), and I think it did some magic to make that work. Still, it might be a place to start…
Dean Edwards Base library - http://dean.edwards.name/weblog/2006/03/base/ - has support for setting up calls to the superclass’s method that you’re overriding. Dojo’s lang OO stuff also has it. Douglas Crockford has writen some fantastic stuff on inheritence in JS, I’m pretty sure he has something that calls super/uber/pickaname.
Well i found your site through Ajaxian too, and I have to say this is pretty much the kind of site I was looking for. I have already saved all your posts to mi computer and I will read them as soon as I got some time.
Great work!
Thanks Orange Agent!
I think its a misconception to believe there is actual class
inheritance within javascript.
What you are showing is prototypal inheritance and appending
a “Class” on the name of your objects.
So i just wanted to make a point that the cool think about
javascript and what you are doing, is that you are dynamically
inherit(augment) methods or properties from other objects without
actually defining a class. This is exactly what you are doing
above.
so its more like “Object Inheritance”, pretty cool, huh…
Here is a link to an article which compares various techniques to implement inheritance in JavaScript (and their benefits and drawbacks) as well as offers truly object oriented inheritance solution for JS:
http://www.soft-amis.org/jsiner/inheritance.html
So that you don’t have to read all the (quite good) article metionned by Andrew, here is a little example of complete inheriting allowing base class calling:
/* The constructor of the Mammal class */
function Mammal(){}
Mammal.prototype.eat=function(){alert(”Eat from Mammal”);}
function Cat() {}
Cat.prototype = new Mammal();
Cat.prototype.constructor=Mammal
Cat.prototype.base=Mammal.prototype
Cat.prototype.eat=function(){this.base.eat();alert(”Eat from Cat”);}
function Persian() {}
Persian.prototype = new Cat();
Persian.prototype.constructor=Cat
Persian.prototype.base=Cat.prototype
Persian.prototype.eat=function(){this.base.eat();alert(”Eat from Persian”);}
var theCat = new Persian();
theCat.eat();
Based on this, you could have a function (which is probably what “FWs” do).
function inherits(newClass, baseClass){
newClass.prototype=new baseClass()
newClass.prototype.constructor=baseClass
newClass.prototype.base=baseClass.prototype
}
and then call
inherits(Persian, Cat);
Also, here is another article that explain JS OO
http://msdn.microsoft.com/msdnmag/issues/07/05/JavaScript/
One interesting thing is that every prototype has a constructor and every constructor has a prototype (not the instance itself). The instance only has a prototype.
I agree with Marco Torre: I think it’s inappropriate to think of JavaScript as a class-based language. Sure, the class metaphor has its own advantages, especially if you’re used to it, but I believe it isn’t the most adequate paradigm for JavaScripting.
As a prototype-based language, I feel that the idea of mixins (http://en.wikipedia.org/wiki/Mixin) are closer in philosophy to the nature of JavaScript. Sadly, I haven’t seen much examples embracing this way of doing things. Is it because OO developers have carried over to JS a crystallized conception of how things should be done in other languages or because mixins aren’t such a great idea after all?
I’d be curious to hear some your thoughts about the subject…
@Luis and Marco
I used a lot of OO techniques in javascript just to work like I did in every other OO languages.
Until the day I understood that OO techniques like inheritance are overused and misused. Then I stopped applying OO to javascript.
The day after this article went out, I secretly wanted to delete it. I don’t like it. We should not do inheritance in javascript. There are hundreds of other better solutions, just use any of those.
To me, it doesn’t really matter if javascript is OO, prototype based or closer to Mixin. Javascript has its own techniques (and inheritance should not be in it) and should be be twisted to fit a particular technique.
I wrote this article for a bad reason. It was my first article since I was on the first page of ajaxian and I didn’t want to lose readers by showing a technique that’s too far from what they see in other languages. It was a stupid idea…
OK, some people here start to sound as purists and not developers… Maybe I’m wrong though… Could anyone give me any concrete drawbacks of using OO in JS? Could anyone give me real benefits of using Mixins? And most of all, could anyone prove that a merge of both worlds depending on the situation isn’t a good approach?
I mean, people here are saying: JS isn’t an OO language, it is a prototype language… but it is proven that it can do it. Isn’t it only that OO wasn’t really developped when JS was released? PHP was far to be an OO language but who here would say that it’s a bad thing that it now is?
Next version of JS WILL support OO statements. Unfortunately, I lost the link to it…
So please, teach me the right from the wrong.
@BK
The next javascript is bullshit. They are taking the classic OO path because “that’s the way a programming language should be”. I really, really, really hate the specs so far.
There’s no right and there’s no wrong. The best you can do is to stop apply OO techniques to javascript just because you’re comfortable in it.
I thank you for your article, Dan. I really think it can be helpful to beginners. Please don’t take my comment too personal. I merely intended to point out that there might be a slightly different, more natural way to envision JS than through inheritance hierarchies.
I still haven’t completely exploited the full potential of mixins, but I think it’s a path worth exploring… Perhaps I should write about this somewhere to illustrate what I have in mind and stimulate conversation…
Finally, I just want to clear out that I didn’t intend to start a debate about OO vs. prototyping, but rather a discussion about how we can best marry the two.
@Luis
I don’t want to start the debate either and I didn’t take it personal. It’s just that you are right on the point to stop thinking of javascript as “it should do as OO”.
I you ever write something on mixin, send me a mail and I’ll try to link to it in a elegant way!
Thanks
Calling a super-class implementation…
Won’t something like,
Mammal.Run.call(catInstance);
do the trick. Or if you’re in a Cat instance (and say want to extend the super-class)
Cat.prototype.Run = function()
{
Mammal.Run.call(this);
// Do more stuff
}
I’m quite sure it would work but the trap here is for maintenance. You are much likely to forget to change one of your “base-class-call” if anything in your “object hierarchy” change. If you use the .base approach, you change one place and everything else will work as expected.
But I’m quite sure that your approach is closer to a prototypal approach.
PROBLEM WITH THIS APPROACH: The problem arises when a closure associated with the object instance is being used to provide private instance members because assigning an instance of that object to the prototype of another constructor will only result in one closure being formed. The privileged methods of the object instance on the prototype are “inherited” by objects created with the constructor but they all access the same, single, closure.
SOLUTION: Parasitic inheritance using Douglas Crockford’s object function and Power Constructor pattern. See Advanced JavaScript video 1 at http://developer.yahoo.com/yui/theater/
Hello,
Sorry, I don’t speak English very well.
JavaScript “like Java”.
var ClassA = Class.create(”ClassA”,function(){
var value = “value:A”;
this.getValue = function(){
return value;
};
this.$$constructor = function(){
};
});
var ClassB = Class.extend(”ClassB”,ClassA,function(){
var value = “value:B”;
this.getValue = function(){
return value + ” ” + this.$$super[0].getValue();
};
this.$$constructor = function(){
};
});
var instB = new ClassB();
alert(instB.getValue());// value:B value:A
You can see more examples in http://www.jsimpleclass.net/
Bye
Hi,
I have tried an different techniques related to JavaScript inheritance subject.
The code and the explanation are to long to post them here so if anyone is interested to take a look over it you can find it at http://www.dotnetcaffe.net under JavaScript category. Fell free to criticize the code in any way you want…just don’t flame :).