Next page | Contents page |

Inheritance

Consider an object type called Person and sub-types Staff and Customer which are specialisations of Person, adding properties (and probably methods) specific to them.


function Person (name, address)
{ 
  this.name = name;
  this.address = address;
} 

function Staff (name, address, staffNo)
{
  Person.call (this, name, address);
  this.staffNo = staffNo;
}
Staff.prototype = Object.create (Person.prototype);
Staff.prototype.constructor = Staff;

function Customer (name, address, orderList)
{
  Person.call (this, name, address);
  this.orderList = orderList;
} 
Customer.prototype = Object.create (Person.prototype);
Customer.prototype.constructor = Customer;

In this way objects of type Staff and Customer inherit all aspects (state and behaviour) of the supertype Person. Any instance of Staff or Customer is also an instance of Person. A Customer IS A Person.

Staff and Customer are said to be subtypes of Person.

Yes, it looks cumbersome but if you can see the pattern and just copy it you will be fine.

Here I have introduced 2 new methods without any explanation: call and create. For more details see MDN call and MDN create.

JavaScript really doesn't have classes - only instances (objects). Cunning!

Having said that, a few years ago (around 2015) a class syntax was added to the language to make things easier for people coming from other languages such as Java and C++. However, all of the new syntax is just "sugar" because browsers and other interpreters of JavaScript first have to convert the class syntax into the prototype language I have shown above. So my feeling is that if you want to make the most efficient programs you should learn the original way of doing it.

Although you will see a lot written about inheritance and the IS-A relationship between classes, in practice you will find that a HAS-A relationship is much more common. In other words, the object type that might be considered for parenthood could just as usefully be the type of a property of the current object.

For more details see MDN object model.

Next page | Contents page |