Features of ES6 Part 9: Classes

Tuesday, October 14, 2014

Historically, many developers learn JavaScript after learning languages like C++, Java, C#, Ruby, or Python. All of these languages have a class keyword, and in many of these languages, the class keyword is the primary building block for constructing software.

In modern times, many developers learn JavaScript as a first language, so the new class keyword in ES6 will be a brand new tool.

Regardless of a developer’s background, the class keyword in JavaScript will play a role similar to the class keyword in other languages. Classes allow developers to define a blueprint for constructing objects. Each object a program creates from the class blueprint will be an object with the same methods and placeholders for data specific to each object.

We’ve always had the capability of building object with data and behavior in JavaScript, but like other ES6 features, the class keyword makes the common practice both succinct and more explicit.

The Keyword

Every class has a name, and a body containing the method definitions for the class.

class Employee {

    hire() {
        this.hired = true;
    }

    getStatus() {
        if(this.hired) {
            return "hired";
        }
    }
}

The above class has two methods: hire and getStatus. Notice we do not need to use the function keyword to define the methods. These methods will be available on every object we create using Employee, and as you can see in the implementation, these methods can save and retrieve state inside the object using the this keyword.

We create Employee objects using the new keyword.

let developer = new Employee();
developer.hire();

expect(developer.hired).toBe(true);
expect(developer.getStatus()).toBe("hired");

Quite often you’ll want an object to initialize itself with specific data right from the start. We can add this initialization logic using a constructor.

Class Constructor and Properties

Every class may specify a constructor. The runtime will invoke the constructor when instantiating a class, and we can use the constructor to initialize state in an object, often by accepting parameters in the constructor method.

class Employee {

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

    getName() {
        return this.name.toUpperCase();
    }
}

let developer = new Employee("Scott");
expect(developer.name).toBe("Scott");
expect(developer.getName()).toBe("SCOTT");

A class can also define a property with get and set to encapsulate a field.

class Employee {

    constructor(name) {
        this._name = name;
    }

    doWork() {
        return `${this._name} is working`;
    }

    get name() {
        return this._name.toUpperCase();
    }

    set name(newName){
        if(newName){ 
            this._name = newName;
        }
    }
}

let developer = new Employee("Scott");
expect(developer.name).toBe("SCOTT");

developer.name = "Alex";
expect(developer.doWork()).toBe("Alex is working");

ES6 also supports class inheritance and  interaction between a class and the class superclass. We’ll take a look at these features in the next installment of the series.


Comments
gravatar abc xyz Tuesday, October 14, 2014
what is ES? ES6?
gravatar Quinntyne Brown Tuesday, October 14, 2014
ES6 looks exciting. Can you check if something is an instance of Employee? I'm assuming that will work? Any upgrades in that area?
gravatar Martin Kirk Tuesday, October 14, 2014
'{$this._name} is working' That can't be right!!!! String formatting without string formatting!!!
gravatar Scott Tuesday, October 14, 2014
@abc, ECMAScript 6, the next version of JavaScript. @Quinntyne: yes, instanceof will work, more on that in a future post! @Martin: template literals in ES6 are awesome!
gravatar Jakub Jedryszek Tuesday, October 14, 2014
This is TypeScript! Would be nice to have classes this without compilation step.
gravatar Jon Preece Saturday, October 18, 2014
Finally, a useful feature of ES6.
Sunday, October 19, 2014
what about private members? I thought it would be take "the best of all worlds" of class notation in javascript, but apparently it is just a syntactic sugar for the this notation (without explicit return object of course).
gravatar Scott Sunday, October 19, 2014
Re:private members, yes, I'll show a technique for managing privates using the new Symbol type in ES6 (a future post in the series).
Comments are closed.

My Pluralsight Courses

K.Scott Allen OdeToCode by K. Scott Allen
What JavaScript Developers Should Know About ECMAScript 2015
The Podcast!