I'm quite new to JavaScript, and I'm trying to understand the idea behind inheritance in JavaScript. I've read a bit about it, and I don't want to mess with prototypes (which I don't yet fully understand) so, I wrote this code using the xtend
module for node.js.
var xtend = require("xtend");
// Human constructor.
// Human is a base class, it can introduce itself, and knows it's age.
function createHuman(name, age) {
function getName() {
return name;
}
function getAge() {
return age;
}
return {
getName : getName,
getAge : getAge,
};
}
// Boy constructor
// Boy *is a* Human
// Boy can play football (but not yet)
function createBoy(name, age) {
function playFootball() {
console.warn("Football skills not implemented yet, but trying", "-", this.getName());
// TODO: implement this
}
return xtend(createHuman(name, age), {
playFootball: playFootball,
})
}
// Girl constructor
// Girl *is a* Human
// Girl can sing (well, almost)
function createGirl(name, age) {
function singASong() {
console.warn("Singing not implemented yet, but trying", "-", this.getName());
// TODO: implement this
}
return xtend(createHuman(name, age), {
singASong: singASong,
})
}
// Hermaphrodite constructor
// Hermaphrodite *is a* Girl **and** Hermaphrodite *is a* Boy, so we have multiple inheritance?
// Hermaphrodite can do what boys and girls can
function createHermaphrodite(name, age) {
return xtend(createGirl(name, age), createBoy(name, age));
}
// Tests:
var boy = createBoy("John", 12);
var boy2 = createBoy("Frank", 10);
var girl = createGirl("Daisy", 7);
var herm = createHermaphrodite("Mel", 24);
console.info("Boy: ", boy.getName(), boy.getAge());
console.info("Boy: ", boy2.getName(), boy2.getAge());
console.info("Girl: ", girl.getName(), girl.getAge());
console.info("Hermaphrodite: ", herm.getName(), herm.getAge());
boy.playFootball();
boy2.playFootball();
girl.singASong();
herm.playFootball();
herm.singASong();
As you can see, I'm not using the usual Class
approach, but instead have a kind of constructors that create objects. The inheritance is made using the xtend
module, which copies properties from another objects. This - I think - also allows for multiple inheritance (see Hermaphrodite
).
Questions:
Can this code be considered good practice? I always thought of JS as a more functional (than OO) language, so not trying to imitate classes, not using the
new
keyword and so on sounded good to me.Is this fast / memory-efficient? I mean - there is an additional object created every time the sub-class instance is created, just to copy the properties (for example, if I create a
Boy
instance, there is aHuman
created just to copy the properties toBoy
).Is there a better / faster / more efficient (or simply: proper) way of doing this? (Pointing to one, remember that I'm a beginner, so be descriptive or I might not understand the answer.)