Hi I’m new in Javascript OO and want to know more about about inheritance. Hope you can provide some advice!
I see this great post:
How to "properly" create a custom object in JavaScript?
which talks about how a class is inherited as I see in other websites, ex.:
function man(x) {
this.x = x;
this.y = 2;
}
man.prototype.name = "man";
man.prototype.two = function() {
this.y = "two";
}
function shawn() {
man.apply(this, arguments);
};
shawn.prototype = new man;
The above post claims that in order not to call “man”‘s constructor while inheriting, one can use a helper like this instead:
function subclassOf(base) {
_subclassOf.prototype= base.prototype;
return new _subclassOf();
}
function _subclassOf() {};
shawn.prototype = subclassOf(man);
While I understand its intention, I don’t see why we can’t call
shawn.prototype = man.prototype;
I see it works exactly the same. Or is there something I’m missing? Thanks in advance!
Well, examples are better than words in my humble opinion. All below examples are using your code, with some additions.
The first example will prove that using
shawn.prototype = new man;you’re calling the constructor twiceAs you see, the constructor is called twice – once with no arguments then with the actual arguments you give it.
The second example just proves that using the
subclassOfsolve that “double calling” issue.The third example shows what’s wrong with your idea of
shawn.prototype = man.prototypeand I’ll explain.shawninherits frommanso I’ve added new method that should affect onlyshawn, calledmarriage(that of course cause him to gain some weight ;)) – that method should not affect the base classmanas it’s not inheriting fromshawn, inheritance is one way only. But…. as you see in the example, ordinarymancan also get married – big problem.Finally, the fourth example shows that using the
subclassOfeverything work fine, asshawninheritsmanproperly, andmarriageis not passed to the base class.Hope this makes some sense! 🙂