I am a Web Designer and Developer
working at GitHub

My passion is building beautiful products and working with wonderful people.

Let’s chat

Classes and Inheritance

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

function Person(name) {
  this.name = name;
}
Person.prototype.getName = function() {
  return this.name;
}

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

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

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

Prototype Chain

Now we bring in the prototype chain. The chain is like an inheritance chain. Developer inherits → from Person. 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 <pre>call</pre> 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

function Developer(name, skills) {
  Person.call(this, name); // we call the Person constructor since it's the superclass
  this.skills = skills;
  this.getSkills = function() {
    return this.skills;
  };
}
Developer.prototype = new Person();
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.

var d = new Developer("Jon Rohan",["Javascript", "HTML", "CSS"]);
// output: Jon Rohan
console.log(d.getName());
// output: Javascript, HTML, CSS
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.

ad

javascript

jonrohan This post was hastily written by Jon Rohan

Creating Triangles in CSS Text Rotation

Related Posts