Javascript/Ecmascript6 Classes

by James Johnson

Javascript didn’t always have built-in support for object oriented classes. I used to use a modified version of John Resig’s Inheritance Script whenever I wanted to implement classes in Javascript. However with the introduction of Ecmascript 6, classes are built-in to the Javascript language. This article discusses how to use the new Ecmascript 6 class syntax.

Contents

Javascript (Ecmascript6) Class Definitions

As expected, classes are declared in Ecmascript6 by using the class keyword:

class Robot {
    // ...
}

Classes may inherit from other classes by using the extends keyword:

class SandwichBot extends Robot {
    // ...
}

Javascript (Ecmascript6) Class Methods

Class methods no longer require the function keyword, and the constructor method must be named constructor:

class Robot {
    constructor(name, ram) {
        this.name = name;
        this.ram = ram;
    }

    interfaceWith(otherRobot) {
        console.debug(this.name + " says hi to " + otherRobot.name);
    }
}

Javascript (Ecmascript6) Super Class Reference

Methods from the base class can be called by using the super keyword:

class SandwichBot extends Robot {
    constructor(name, ram, sandwichTypes) {
        super(name, ram);
        this.sandwichTypes = sandwichTypes;
    }

    interfaceWith(otherRobot) {
        super.interfaceWith(otherRobot);
        var n = this.sandwichTypes.length;
        var randSandwich = this.sandwichTypes[Math.floor(Math.random() * n)]
        console.debug([
            this.name,
            "offers",
            otherRobot.name,
            "a",
            randSandwich,
            "sandwich"
        ].join(" "));
    }
}

Javascript (Ecmascript6) Getters and Setters

Getters and setters can now be created using the get and set keywords when declaring a class method:

class SandwichBot extends Robot {
    // ...
    get numSandwiches() { return this.sandwichTypes.length; };
    // ...
}

Javascript (Ecmascript6) Static Members

The static keyword allows members of classes to be static (i.e., accessible through a class without requiring a class instance):

class Robot {
    static get laws() {
        return [
            "Do not injure human beings, directly or indirectly",
            "Obey all orders given",
            "Protect yo-self!"
        ];
    }

    // ...
}

console.debug("Robot laws:")
for(var law of Robot.laws) {
    console.debug("  " + law);
}

Full Javascript (Ecmascript6) Class Example

Below is my full example that all of the snippets above were taken from:

"use strict";

class Robot {
    static get laws() {
        return [
            "Do not injure human beings, directly or indirectly",
            "Obey all orders given",
            "Protect yo-self!"
        ];
    }

    // -----------

    constructor(name, ram) {
        this.name = name;
        this.ram = ram;
    }

    interfaceWith(otherRobot) {
        console.debug(this.name + " says hi to " + otherRobot.name);
    }
}

class SandwichBot extends Robot {
    constructor(name, ram, sandwichTypes) {
        super(name, ram);
        this.sandwichTypes = sandwichTypes;
    }

    get numSandwiches() { return this.sandwichTypes.length; };

    interfaceWith(otherRobot) {
        super.interfaceWith(otherRobot);
        var n = this.sandwichTypes.length;
        var randSandwich = this.sandwichTypes[Math.floor(Math.random() * n)]
        console.debug([
            this.name,
            "offers",
            otherRobot.name,
            "a",
            randSandwich,
            "sandwich"
        ].join(" "));
    }
}

var r2d4 = new Robot("r2d4", 1024*1024);
var c5p0 = new Robot("c5p0", 1024*4096);

r2d4.interfaceWith(c5p0);

var sanders = new SandwichBot("Sanders", 128, ["blt", "pbj", "pbh"])
sanders.interfaceWith(c5p0);

console.debug("Robot laws:")
for(var law of Robot.laws) {
    console.debug("  " + law);
}

console.debug("Sanders can make " + sanders.numSandwiches + " different sandwiches");

Running this script in a browser yields the following output written to the console:

r2d4 says hi to c5p0
Sanders says hi to c5p0
Sanders offers c5p0 a blt sandwich
Robot laws:
  Do not injure human beings, directly or indirectly
  Obey all orders given
  Protect yo-self!
Sanders can make 3 different sandwiches

Notice how the statement "use strict"; is the first statement in the javascript file. Browsers will not use the latest javascript features if the use-strict statement is not the first line.

For example, if I run the code without "use strict" in Google Chrome, I get this error:

Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode