OdeToCode IC Logo

Static Members in ES6

Monday, February 2, 2015

In previous posts, we looked at classes in ES6, but I never gave an example using the static keyword.

A class may contain one or more methods defined with the keyword static.

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

    static convert(thing) {
        if(thing.name) {
            return new Employee(thing.name);
        }
    }
}

Like other languages with static class members, the static keyword will create a method associated with the class, and not with an instance of the class. In other words, you can only reach a static method using the name of the class.

expect(Employee.convert).toBeDefined();
expect(new Employee().convert).toBeUndefined();

Static methods have no access to the fields, properties, and methods defined on an instance of the class using this. For example, the convert method would not be able to use this._name to get to the _name field of an Employee object, as the this pointer inside of convert will never reference an Employee object. However, static methods are often useful and can play the roles of factory methods, conversion methods, or general class helper methods.

let person = { name: "Scott" };
let newHire = Employee.convert(person);
expect(newHire.name).toBe("Scott");

The behavior of static methods is explained by what happens behind the scenes. A static method of a class is associated with the constructor function and not the prototype object like the instance members we saw in the last section.

var Employee = function(name) {
    // ...
};

Employee.convert = function(thing) {
    // ...
};