Three Ways to Create a Javascript Class

Posted in Articles

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Of the three ways to create a Javascript class, we start off with the most traditional way.

1. Using new operator on a constructor function to create Javascript class

In Javascript, functions are objects.  The following “function” acts as a “class”.  We can create method of the class by adding the function to the prototype property (saves memory that way).

javascript class as function

javascript class as function

Here we named our “class” with a capital letter “Car” (to indicate class).   We create an instance of that class with the “new” operator.  That instance is saved to variable myCar (lowercase to indicate instance).  With this instance, we can call  the methods of the class.  This method of creating classes is “classical inheritance”, because it is similar to how some of the other languages create classes.

2.  Using Object.create to create Javascript Class

A more “Javascript” way of creating class is to use “prototypical inheritance” that does not involve the “new” operator.

prototypical inheritance using Object create

prototypical inheritance using Object.create

You create an object (or “class”) using object literal.  And then create new instances of this class by using Object.create and then override whatever properties and methods you need to.  Modern browsers and Internet Explorer 9 can use Object.create.  IE8 will require a polyfill.

3.  ES6 Classes

In the latest version of ES6 of Javascript, you have the “class” keyword and the ‘constructor’ function …

es6 classes

es6 classes

At the time of this writing (August 2015) some browsers still does not support ES6.  So you can transpile this code down to ES5 using Traceur and TypeScript.

You can also “extend” a class like this …

es6 extends keyword

es6 extends keyword

Here the class “SUV” extends “Car”.  Its constructor calls the parent constructor with “super”.  You can overwrite the parent method easily as shown above.