Created
April 27, 2015 04:39
-
-
Save sheniff/1a24f9b52470afe62740 to your computer and use it in GitHub Desktop.
Inheriting a parent class in JS. Instantiating parent class in prototype to make only instance methods to be available for child class.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Class generator | |
| var Class = function(parentCls) { | |
| var Klass = function() { | |
| this.init.apply(this, arguments); | |
| }; | |
| if(parentCls){ | |
| var subClass = function(){}; | |
| subClass.prototype = parentCls.prototype; | |
| Klass.prototype = new subClass; | |
| } | |
| Klass.prototype.init = function() {}; | |
| return Klass; | |
| }; | |
| // Parent Class | |
| var ParentClass = new Class; | |
| ParentClass.prototype.method = function() { | |
| console.log('calling the parent method'); | |
| }; | |
| ParentClass.prototype.variable = 'a string!'; | |
| ParentClass.staticMethod = function() { | |
| console.log('parent\'s static method'); | |
| } | |
| // Child Class | |
| var ChildClass = new Class(ParentClass); | |
| console.log('DA PARENT:'); | |
| var myParent = new ParentClass; | |
| myParent.method(); | |
| ParentClass.staticMethod(); | |
| console.log('the variable: ', myParent.variable); | |
| console.log('DA CHILD:'); | |
| var myChild = new ChildClass; | |
| myChild.method(); // Will call parent function | |
| console.log('child class should not inherit parent\'s static methods:', myChild.staticMethod); | |
| console.log('the variable in child: ', myChild.variable); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment