ES6 Everyday: Static Class Members

Along with classes, ES6 also gives us static class members.

First, let’s remind ourselves of instance members:

class PhoneNumber
{
  constructor(number)
  {
    var numberParts = number.split('-');
    this.areaCode = numberParts[0];
    this.exchange = numberParts[1];
    this.lineNumber = numberParts[2];
  }
  
  getRawNumber()
  {
    return this.areaCode + this.exchange + this.lineNumber;
  }
  
  getFormattedNumber()
  {
    return `(${this.areaCode}) ${this.exchange}-${this.lineNumber}`;
  }
}

So here we have a PhoneNumber class that takes in a number string, in the format XXX-XXX-XXXX, and splits it up into various properties and methods that can be referenced using an instance of the PhoneNumber class:

var newNumber = new PhoneNumber("123-456-7890");
console.log(newNumber.exchange); // 456
console.log(newNumber.getRawNumber()); // 1234567890
console.log(newNumber.getFormattedNumber()); // (123) 456-7890

These properties and methods are instance members. In other words, we can’t access them through the class itself:

console.log(PhoneNumber.getRawNumber());
// TypeError: PhoneNumber.getRawNumber is not a function at eval

With the static keyword, however, we can define static members:

class PhoneNumber
{
  // (Pretend all the stuff from above is here too!)
  
  static isValidNumber(input)
  {
    return /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/.test(input);
  }
}

console.log(PhoneNumber.isValidNumber('123456')); // false
console.log(PhoneNumber.isValidNumber('123-456-7890')); // true

As you can see, this method is now available at the class level. In fact, we can’t call this method from an instance of the class:

console.log(newNumber.isValidNumber('123-456-7890'));
// TypeError: newNumber.isValidNumber is not a function at eval

Give it a spin for yourself in this ES6 Fiddle!

Resources