The most common JavaScript prototypical inheritance pattern then resembles your code can be seen on MDN.
The essence is that you need to assign a prototype for your inheriting types that is a new object with the prototype set to the required base type. Then you also call the base type's constructor function inside the inheriting constructor. For completeness and to maintain proper structure, you also reset the constructor of the newly created prototype object (which doesn't point to the correct function if you don't).
After creating the prototype object, you can add type-level functions to it (It can also be done in the Object.create
call, but personally I like that less)
The entire code would look like (Also added optional constructor initialization values):
function Employee(name, dept) {
this.name = name || '';
this.dept = dept || 'general';
}
function WorkerBee(name, dept) {
Employee.call(this, name, dept);
this.projects = [];
}
WorkerBee.prototype = Object.create(Employee.prototype);
WorkerBee.prototype.constructor = WorkerBee;
WorkerBee.prototype.addProject = function(project) { this.projects.push(project); };
// Same for Manager...
function SalesPerson(name) {
WorkerBee.call(this, name, 'sales');
this.quota = 100;
}
SalesPerson.prototype = Object.create(WorkerBee.prototype);
SalesPerson.prototype.constructor = SalesPerson;
// Same for Engineer
var mark = new WorkerBee('Mark');
var noName = new WorkerBee();
var fred = new SalesPerson('Fred');
fred.addProject('Sell ice to an eskimo');
console.log(mark, noName, fred);
With ES2015 classes all that redundant code becomes much more concise:
'use strict'
class Employee {
constructor(name, dept) {
this.name = name || '';
this.dept = dept || 'general';
}
}
class WorkerBee extends Employee {
constructor(name, dept) {
super(name, dept);
this.projects = [];
}
addProject(project) { this.projects.push(project) }
}
class SalesPerson extends WorkerBee {
constructor(name) {
super(name, 'sales');
this.quota = 100;
}
}
var mark = new WorkerBee('Mark');
var noName = new WorkerBee();
var fred = new SalesPerson('Fred');
fred.addProject('Sell ice to an eskimo');
console.log(mark, noName, fred);