ES6 Classes

Objectives

  • Explain the difference between function constructors and ES6 classes
  • Use super to refer to the subclass's parent class
  • List the different types of methods a class can have and explain the difference between them

Under the hood, ES6 classes are not something that is radically new: They mainly provide more convenient syntax to create old-school constructor functions.

 - Axel Rauschmayer

var Dog = function(name){
    this.name = name;
}

Dog.prototype.call = function(){
    return "Come here " + this.name;
}

Dog.prototype.bark = function(){
    return "Bow wow";
}

// ES5 way

var myDog = new Dog('Twiggy');
myDog.bark() // 'Bow wow'
class Dog {

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

    call(){
        return "Come here " + this.name;
    }

    bark(){
        return "Bow wow"
    }

}

// ES6 way

var myDog = new Dog('Twiggy');
myDog.bark() // 'Bow wow'
class Dog {

    public Dog(String name){
        this.name = name;
    }

    public static String call(){
        return 'Come here ' + this.name;
    }

    public static String bark(){
        return 'Bow wow';
    }

}

//  Java

Base Classes

Class Expression vs Class Declaration




  •  
  • Analogous to that of anonymous and named function expressions, with one exception:
  • Class declarations are not hoisted (function declarations are)
// Class expression
class Food {}

// Class declaration
var Food = {}
// OR
var Food = goodFood{}

Derived Classes



class Dog extends Animal {
    // class body
}

A derived class can't contain an empty constructor.

 It can, however, contain no constructor.

You must call `super` in the constructor of a derived class before you use `this`.

Methods

Constructors

  • It's the only method of a class from which you can make a superconstructor call
  • It handles all the dirty work of setting up the prototype chain properly
  • It acts as the definition of the class.

Constructors

  • Can't be called without `new` keyword




     
  • Cool trick to use (new.target):
class Car{
    
    constructor(make, model){
        this.make = make;
        this.model = model;
    }
}

var ford = Car('Ford', 'Elantra'); // undefined
class Car{
    
    constructor(make, model){
        if(!new.target) return new Car(make, model);
        this.make = make;
        this.model = model;
    }
}

var ford = Car('Ford', 'Elantra'); // we good!

Static

Methods on the constructor function itself, which are not available on instances of the class.

Prototype

Any method that isn't a constructor or a static method

 

The name comes from the fact that we used to achieve this functionality by attaching functions to the .prototype of functions-as-constructors

In-depth reading:

ES6 Classes

By Dize Hacioglu

ES6 Classes

  • 259