JavaScript Classes ES5 vs ES6

Made by Marvin Drude

JavaScript Classes ES5 vs ES6

I just wanted to show the difference between classes in JavaScript ES5 and ES6. Let’s start with ES5 and the decleration of the class itself.

function Animal(age) {
    this.age = age;
}

As you can see, we declare a class and its constructor just like another function. Having done this we can continue with beginning to write methods of the class Animal.

Animal.prototype.getAge = function() {
    return this.age;
}

Animal.prototype.toString = function() {
    return "Animal is " + this.age + " years old";
}

Alright, we setup a very simple class and you probably wonder how inheritance works now. In ES5 I really don’t like the way we have to realise it.

function Moose(age, color) {
    Animal.call(this, age);
    this.color = color;
}

Moose.prototype = Object.create(Animal.prototype);
Moose.prototype.constructor = Moose;

So this non-intuitive code allowed us to have an inheritance between super class Animal und sub class Moose. But now we can even call super methods inside methods of sub class Moose.

Moose.prototype.toString = function() {
    return Animal.prototype.toString.call(this) 
        + "and is of color " + this.color;
};

var moose = new Moose(20, "blue");
moose.toString(); 
// returns "Animal is 20 years old and is of color blue"

ES6 Syntax Sugar

In ES6 we finally have the possibility to use a new synax for classes. It is important to know that this does not change anything under the hood of JavaScript itself. It is just a change in syntax.

class Animal {

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

    getAge() {
        return this.age;
    }

    toString() {
        return "Animal is " + this.age + " years old.";
    }

}

As you can see here, the way we declare a class is very intuitive and similar to other languages.

class Moose extends Animal {

    constructor(age, color) {
        super(age); // has to be called first
        this.color = color;
    }

    toString() {
        return super.toString() + " and is of color " + this.color;
    }

}

Even the inheritance is now very maintainable and readable. My conclusion is that JavaScript ES6 classes are a good starting point in improving the language.