I also have this running example on jsfiddle
Sample:
function Animal(o) {
o.class = Animal;
o.name = o.name ? o.name : "Animal"; // Defaults
o.age = o.age ? o.age : 0; // Defaults
o.weight = o.weight ? o.weight : 0; // Defaults
o.say = o.say ? o.say : "?";
Animal.isOnEarth = true; // "static variable"
return o;
}
function Cow(o) {
o.class = Cow;
o.name = o.name ? o.name : "Cow"; // Defaults
o.milk = o.milk ? o.milk : 0; // Defaults
o.say = o.say ? o.say : "MOOO";
return Animal(o); //Inheritence
}
function Dog(o) {
o.class = Dog;
o.isCrazyLab = o.isCrazyLab ? o.isCrazyLab : false;
o.say = o.say ? o.say : "WOOF";
return Animal(o) //Inheritence;
}
function Labradore(o) {
o.class = Labradore;
o.isCrazyLab = o.isCrazyLab ? o.isCrazyLab : true;
o.say = o.say ? o.say : "YARRWL";
return Dog(o) //Inheritence;
}
var cow = Cow({});
var bessy = Cow({name:"bessy",milk:25});
var spot = Dog({name:"spot"});
var hugo = Labradore({name:"hugo"});
document.write("True or false, all these animals live on earth " + Animal.isOnEarth + " A cow says " + cow.say + "... bessy's name is " + bessy.name + " a " + spot.name + " says " + spot.say + " " + hugo.name + " says " + hugo.say);
I’ve got a small project that I’m working on and I wanted to implement a type of inheritance. I looked at some of the samples online but I don’t quite understand why it would be important to go through all the rigamaroll of modifying basic behaviors in javascript. To me it feels like extending the class concepts of javascript to make it “feel” like another language may save a few lines but doesn’t appear to add much core functionality. However, I am more than happy to be schooled 🙂
Some questions
Is there any libraries that work in this manner?
Any online examples of the pros and cons of doing this?
Is there a fundamental reason NOT to do this?
Any general thoughts?
That’s not really inheritance, it’s basically copying. Not that terminology necessarily matters here. 🙂
The main downsides I see are:
instanceofwon’t worknewwith them.Off-topic: A couple of notes:
classis a reserved word in JavaScript. You shouldn’t use it as an identifier, just as you wouldn’t usefororifas an identifier.You can simplify a bit by using the curiously-powerful
||operator, e.g.: