Object Orientation In JavaScript II [Inheritance]
well there are two ways inheritance can be implemented in JavaScript this code explains how the first way
1: function superClass (){ 2: this.superClassMember = function(){ 3: alert ('this is executed from the Super Class'); 4: }
5: }
6:
7: // and then
8:
9: function subClass(){ 10: // the next two lines are the inheritence implementation
11: this.inheritence = superClass;
12: this.inheritence();
13:
14: // then the rest of the sub class implemenation
15:
16: this.subClassMember = function (){ 17: alert ('this is executed from the Sub Class'); 18: }
19: }
now in the previous code snippet check out line 11 actually all that was done is that a new attribute was created for the subclass and its value now references the super class then
in line 12 as the attribute actually references a method we can simply invoke it and as long as we're actually in the scope of the second function the this code referencing "this"would simply be running in the second method context which automatically gives all the internals of the super class to the subclass
and then simply you can do this
1: var subObj = new subClass();
2: subObj.subClassMember();
3: // and that would make the alert from the subClass Appear which is normal
4: // the cool line to execute is this
5: subObj.superClassMember();
6: // and it would display the message from the superClass Method
and there's also this, you can use prototyping to have all the functionality of a class inside another
it would look like this
1: function superClass (){ 2: this.superClassMember = function(){ 3: alert ('this is executed from the Super Class'); 4: }
5: }
6: // and then the sub class
7: function subClass(){ 8: this.subClassMember = function (){ 9: alert ('this is executed from the Sub Class'); 10: }
11: }
12:
13: // inheritence is implemented in the next line
14: subClass.prototype = new superClass;
and of course you can use the members in the subclass when instantiating the second you can use the same code in the second snippet in this post
this post is part of a series starting here