Javascript Inheritance, examples
Ok, so here we are. We've seen the code to actually achieve true object orientation in javascript, albeit a simulated variant of the paradigm, but still, there it is. Now, as most developers think their stuff is the right, I had neglected to see who has thought like I had, "What if javascript really simulated OO, not just gave you a cheap knockoff," (see methodology #3 below).
In an attempt to rectify said foolish ambition, I decided to do a little research. I probably haven't done enough yet, but I found several articles dealing with this exact topic. The site twologic has two (one, two), as well as dean edwards, and of course, douglas crockford. Now, I'm really sorry to say it, but none of these examples really comes close. I mean, twologic has done a decent job of making the super calls accessible, but making it first for prototype was a really bad idea, since it can be made much simpler from scratch.
Examples
Now for some examples of use. Here is a somewhat classic example, using our favorite subject on basic object oriented principles, the animal.
var Animal = function(name, sound) {
this.sound = sound;
};
Animal.prototype = {
makeSound: function() {
alert(this.name + " says " + this.sound);
}
};
var Cat = function() {
this.superclass("Cat", "meowwww!!!");
};
Cat.prototype = {
makeSound: function() {
this.superclass.makeSound();
alert("... meow?");
}
};
var Dog = function(owner) {
this.superclass("Dog", "woof!");
this.owner = owner;
};
Dog.prototype = {
makeSound: function() {
alert("I wuv " + this.owner);
this.superclass.makeSound();
}
};
Object.inherit(Cat, Animal);
Object.inherit(Dog, Animal);
var cat = new Cat();
var dog = new Dog("Bob Dylan");
cat.makeSound();
dog.makeSound();As you can see, there should be a fair amount of familiarity with this if you come from most any background, I assume. However, fellow java programmers will recognize it rather quickly. The only real difference is the need for this which is a basic javascript requirement, and superclass instead of super which was just a whim (or perhaps influenced by some library, like YUI, I dunno...).
At any rate, I hope you can see the differences between my implementation, which is completely intuitive to programmers familiar with other oo languages, and everything else, which at present, doesn't seem to go the full distance for one reason or another. Also, you should notice my implementation is very small, and makes twice as much sense to anyone wishing to learn from the code.
Any time now, I may be told I'm quite out of line, or have made some dumb mistake... if so, I'll simply edit this post and claim I knew it all along.. Until then, check out my site for the developing base of clean code just like this, and please leave comments so I know what you're thinking.
0 comments:
Post a Comment