ES6 Classes

There was once a time when we had to create classes manually with libraries, those dark times have long since past. These days we can create classes using a new amazing syntax:

Internally classes in ES6 compile to functions. The functions aren't all that different than older techniques for creating classes. The above compiles to something that looks a bit like:


function _createClass(klass, methods) {
  // lots of stuff to turn the methods into properties on a object
  const cat = {
    talk() {
    }
  }

  return cat
}

function Cat(name) {
  this.name = name;

  return  _createClass(Cat, [{
    key: 'talk',
    value: function talk() {
      return 'Meow my name is ' + this.name;
    }
  }, {
    key: 'awesomeLevel',
    get: function get() {
      return this.level + 1;
    },
    set: function set(level) {
      this.level = level;
    }
  }]);
}

Classes are really kind of simple and just syntatic sugar over objects and prototypal inheritance.

Getters and Setters

You can add a getter and setter for a prop with the get and set keywords:

class Cat {
  constructor(name) {
    this.name = name
  }

  get awesomeLevel() {
    return this.level + 1
  }

  set awesomeLevel(level) {
    this.level = level
  }
}

It is important you don't set or get a property of the same name in a getter or setter. The following would lead to a stack overflow:

class Cat {
  constructor(name) {
    this.name = name
  }

  set name(name) {
    this.name = name
  }
}

Static Methods

You can add a method to the class itself by using the static keyword. It looks like this:

That does it! Now you are Neo. You know classes!