I am looking to do some inheritance with JavaScript and while searching the inter-webs I found many examples and multiple ways and implementations of inheritance. I eventually found one that I liked because of it's simplicity and from all the reading and learning I came up with this approach:
var Animal = function () {
var self = this;
self.legs = 4;
self.makeNoise = function () {
return "noise";
};
};
var Dog = function () {
var self = new Animal();
self.base = {
makeNoise: self.makeNoise
};
self.makeNoise = function () {
var noise = "bark \n";
noise += self.base.makeNoise();
return noise;
};
return self;
};
var Monkey = function () {
var self = new Animal();
self.base = {
makeNoise: self.makeNoise
};
self.legs = 2;
self.makeNoise = function () {
var noise = "weird monkey sound \n";
noise += self.base.makeNoise();
return noise;
};
return self;
};
$("#monkey").click(function () {
var monkey = new Monkey();
var result = "Legs: " + monkey.legs + "\n";
result += "Noise: " + monkey.makeNoise();
alert(result);
});
$("#dog").click(function () {
var dog = new Dog();
var result = "Legs: " + dog.legs + "\n";
result += "Noise: " + dog.makeNoise();
alert(result);
});
You can find a working JSFiddle here.
As you can see from the code, I keep a reference of the original base function in a base
variable so I can then call base
. Do you see anything wrong with this approach? Any shortcomings, overseen issues that might arise in the future, anything I'm missing?