Thoughts and notes on inheritance in javascript.
You can use the built in .call() method to extend a javascript class.
Syntax:
1 2 3 4 | var InheritClass = function() {} var YourClass = function() { InheritClass.call(this); } |
An example with “Animal”. Inherit an Animal class inside a Cow class.
Remember to create a new instance of Cow. Only in the object instance can you call the methods and properties.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | var Animal = function() { this.speak = "no speak set"; this.food = "no food set"; this.action; this.says = function() { console.log(this.speak); }; this.eats = function() { console.log(this.food); }; }; var Cow = function () { Animal.call(this); }; // Cow.says(); // This wont work //You have to create a new object as indicated below var Bessie = new Cow(); //You will see the default values Bessie.says(); Bessie.eats(); Bessie.speak = "Moo"; Bessie.food = "Hay"; //You see your newly set values Bessie.says(); Bessie.eats(); |
So can you use the same concept to inherit from multiple classes? Yes.
You can inherit from multiple classes and keep adding to the current class.
Eg
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | var Animal = function() { this.speak = "no speak set"; this.food = "no food set"; this.action; this.says = function() { console.log(this.speak); }; this.eats = function() { console.log(this.food); }; this.actions = function() { console.log(this.action); }; }; var Farm = function() { this.farm = "no farm"; this.whichFarm = function() { console.log(this.farm); }; }; var Cow = function () { Animal.call(this); Farm.call(this); }; var Bessie = new Cow(); Bessie.says(); Bessie.eats(); Bessie.whichFarm(); Bessie.speak = "Moo"; Bessie.food = "Hay"; Bessie.farm = "Old Mc Donald's"; Bessie.says(); Bessie.eats(); Bessie.whichFarm(); |