Javascript inheritance

Date: 2016-07-12

Source: http://stackoverflow.com/a/7510136

function inherit(childClass,parentClass) {
  var f=function(){}; // defining temp empty function
  f.prototype=parentClass.prototype;
  f.prototype.constructor=f;

  childClass.prototype=new f;

  childClass.prototype.constructor=childClass; // restoring proper constructor for child class
  parentClass.prototype.constructor=parentClass; // restoring proper constructor for parent class
}

Usage:


Employee = function Employee(/*list of constructor parameters, if needed*/) {
}
Employee.prototype.paygrade = 1;
Employee.prototype.name = "";
Employee.prototype.dept = "general";
Employee.prototype.salary = function() {
  return this.paygrade * 30000;
}


WorkerBee = function WorkerBee(/*list of constructor parameters, if needed*/) {
  this.projects = ["Project1", "Project2"];
}
inherit(WorkerBee,Employee); // for this implementation of *inherit* must be placed just after defining constructor
WorkerBee.prototype.paygrade = 2;
WorkerBee.prototype.projects = null; // only literals and function-methods can properly initialized for instances with prototype


Engineer = function Engineer(/*list of constructor parameters, if needed*/) {
}
inherit(Engineer,WorkerBee);
Engineer.prototype.dept = "Programming";
Engineer.prototype.language = "Objective-C";




var jane = new Engineer(/*Engineer parameters if needed*/);
var jill = new Engineer(/*Engineer parameters if needed*/);
var cow = new Employee(/*Employee parameters if needed*/);
3870cookie-checkJavascript inheritance