A Web Developer's Field Guide

Classes and Inheritance

Category
JAVASCRIPT
Last Update
15 October 2010
Tweet
Author

Object oriented JavaScript is everywhere today, and its the type of thing that takes a developer from someone tinkering with JavaScript on the path to becoming a JavaScript ninja. In this post I’m gonna discuss the basics of creating a JavaScript class, and a subclass which inherits methods from the superclass.

A JavaScript Class

Let’s start out with a basic class. The Person class has one method getName, when you create a new instance of the Person class you will pass in the Person’s name.

The Person class

1 function Person(name) {
2   this.name = name;
3 }
4 Person.prototype.getName = function() {
5   return this.name;
6 }

So in the above example I created a Person class with a name attribute and a function to retrieve the name. Now I’ll create a new person, “Jon Rohan”.

1 var p = new Person("Jon Rohan");
2 // output: Jon Rohan
3 console.log(p.getName());

The

p
is a new Person with the name “Jon Rohan”, when I log to the console the result of
p.getName()
it returns “Jon Rohan”.

Prototype Chain

Now we bring in the prototype chain. The chain is like an inheritance chain. Developer inherits → from Person. So we are defining a Developer as a Person, cause developers are people too. ;-) The developer takes the name attribute like Person, and an array of skills. The first line of the Developer class is to

call
the Person class. This calls the Person’s constructor. The Developer class also has a new method getSkills, because a Person is too general to have skills, but as a Developer, there are skills that they have.

We also need to set Developer.prototype to the Person’s prototype, by creating a new Person. Now we set the Developer’s constructor to the Developer. And we have successfully created a prototype chain from Developer to Person.

The Developer Class

1 function Developer(name, skills) {
2   Person.call(this, name); // we call the Person constructor since it's the superclass
3   this.skills = skills;
4   this.getSkills = function() {
5     return this.skills;
6   };
7 }
8 Developer.prototype = new Person();
9 Developer.prototype.constructor = Developer;

Now we’ll create a new Developer, with the name “Jon Rohan” and skills [“Javascript”, “HTML”, “CSS”]. When we create the new developer, he’ll also have the getName method inherited from the Person class, and the getSkills method from the Developer class.

1 var d = new Developer("Jon Rohan",["Javascript", "HTML", "CSS"]);
2 // output: Jon Rohan
3 console.log(d.getName());
4 // output: Javascript, HTML, CSS
5 console.log(d.getSkills().join(", "));

This is the basic ideas behind Object Oriented Programming in JavaScript, I’ve only really scratched the surface in JavaScript OOP.