There are hundreds of ways to do inheritance in javascript but a single one is simpler, cleanier and prettier than all the other ones.
A one-liner
To inherit a class in javascript, it’s a one-liner- TheSubClass.prototype = new TheParentClass();
Where to write the one-liner
The problem with that one-liner is where should it goes? Once again, the answer is simple : after the constructor of the sub-class. It may look strange but it is extremely effective.- /* The constructor of the Mammal class */
- function Mammal() {
- }
- /* The constructor of the Cat class */
- function Cat() {
- }
- // The magic that inherits Cat from Mammal is here!!!!!
- Cat.prototype = new Mammal();
Is this true inheritance?
In the hundreds of other ways of inheriting classes in javascript, I think that this is the only one that is a true inheritance. What do I mean by true inheritance? I mean that javascript recognizes it as a sub-class of the class. Check this out!- /* Above code goes here */
- // Create a cat
- var theCat = new Cat();
- // Check if the cat is an instance of the Cat class
- if (theCat instanceof Cat) {
- alert("theCat is an instance of the Cat class");
- }
- // Check if the cat is an instance of the Mammal class
- if (theCat instanceof Mammal) {
- alert("theCat is an instance of the Mammal class");
- }
0 comments:
Post a Comment