Skip to content

Instantly share code, notes, and snippets.

@sheniff
Created April 27, 2015 04:39
Show Gist options
  • Select an option

  • Save sheniff/1a24f9b52470afe62740 to your computer and use it in GitHub Desktop.

Select an option

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.
// 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