Classes

  1. var monsterHealth = Symbol(); // Symbol() is a JS method that acts like a GUID generator
  2. var monsterSpeed = Symbol();
  3. class Monster {
  4. constructor(name, health, speed) {
  5. this.name = name;
  6. this[monsterHealth] = health;
  7. this[monsterSpeed] = speed;
  8. }
  9. // getter
  10. get isAlive() {
  11. return this[monsterHealth] > 0;
  12. }
  13. // setter
  14. set isAlive(alive) {
  15. if(!alive) this[monsterHealth] = 0;
  16. }
  17. // method
  18. attack(target) {
  19. console.log(this.name + ' attacks ' + target.name);
  20. }
  21. }
  22. var Jorge = new Monster('Jorge', 3);
  23. Jorge.isAlive; // true
  24. jorge.isAlive = false;
  25. console.log(jorge.isAlive); // false

Classes gotchas

The following will fall in a cyclical death trap because the setter for name is already in the constructor.

  1. class Monster {
  2. constructor(name) {
  3. this.name = name;
  4. }
  5. // setter
  6. set name (name) {
  7. this.name = name;
  8. }
  9. }
  10. var Jorge = new Monster('Jorge', 3);
  11. jorge.name = 'kevin';

Classes don’t hoist.

Extend classes

  1. class Godzilla extends Monster {
  2. constructor() {
  3. super('Godzilla', 10000);
  4. }
  5. attack(target) {
  6. super(target); // will call the Monster attack method
  7. }
  8. }

Static methods destructuring

  1. class Monster {
  2. static sayHello () {
  3. console.log('hello');
  4. }
  5. }
  6. const { sayHello } = Monster;
  7. sayHello(); // 'hello'