A Guide To ES6 Classes

Last updated: March 27, 2015

You might have noticed I have been writing about ES6 a lot lately. This is because I am excited about ES6 and thanks to the use of transpilers we can actually use it right now until browsers catch up.

What are Javascript classes?

In many ways, they are a sham. Javascript classes don’t really exist other than for cosmetic reasons. They are syntactic sugar over existing Javascript prototypical inheritance. The reason for this was to ensure backwards compatibility, classes merely give you a cleaner way to organise your code.

If you’re still confused, here is an example showing the ES6 way of writing a class and the ES5 way of doing the same thing (just not as pretty).

An example of ES5 and ES6 classes syntax

The ES6 way:

class someClass {
    constructor(name, age) {
        this.name = name;
        this.age = age;
 }

    sayName() {
        alert(this.name);
    }

    sayAge() {
        alert(this.age);
    }
}

var myInstance = new someClass('dwayne', 27);
myInstance.sayName();

Now for the ES5 way of writing a “class”

function someClass(name, age) {
    this.name = name;
    this.age = age;
}

someClass.prototype.sayName = function() {
    alert(this.name);
}

someClass.prototype.sayAge = function() {
    alert(this.age);
}

var myInstance = new someClass('dwayne', 27);
myInstance.sayName();

You can probably notice the differences between the two. We instantiate our classes the same way we would if we were building our code from an ES5 perspective, but there are a few subtle differences.

An example of ES6 class inheritance

class someClass {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    
    sayName() {
        alert(this.name);
    }
}

class Child extends someClass {
    constructor(name, age) {
        super(name, age);
    }
    
    // Override the someClass method above
    sayName() {
        // This will call someClass.sayName() triggering the old alert
        // Which will just display our name
        super.sayName();
        
        // This will trigger the new alert which has labels and our age
        alert('Name:' + this.name + ' Age:' + this.age);
    }
}

var myChild = new Child('dwayne', 27);
myChild.sayName();

As you can see, classes are extremely flexible especially when extending a base class and having the ability to easily override a parent method without needing to write any boilerplate logic to do so.

Introducing super()

In the ES6 classes syntax we have access to a function called super() which essentially just calls the parent function depending on the context and then returns the result. This isn’t a new premise, it exists in various forms and previously to achieve such functionality in Javascript required the use of call or apply.

Most use cases will just use the super() method inside of a class constructor. Calling super.parentMethodName() from within a child class will call the base class you inherited. If you inherited a class called ‘Core’ and your child class is called ‘AjaxComponent’ calling super.AjaxComponent() from within AjaxComponent’s constructor will call the parent constructor first.

There surprisingly is not a lot of documentation or examples out there currently that newbie developers can reference when working out when to use the super() method and where you should use it. So hopefully this clears up any confusion you might have around using this particular method in an ES6 class.

Why should I use ES6 classes?

Besides the obvious advantages of easier to read code? Being able to write well-structured Javascript that resembles a more realistic object-oriented programming language is a huge benefit. While Javascript classes are definitely not on the same scale as Java or C++, they are a step in the right direction as Javascript matures.

Classes at least for now are purely cosmetic, but there are plans to introduce object-oriented syntax like; static, public, private in ES7, but we’ll wait and see if they make the cut.

However, when coupled with a strong IDE and tooling, ES6 classes can be powerful in that they can be analysed by the IDE and we are given more options for tracing methods (especially when extending parent classes). My favourite ES6 capable IDE of choice is Webstorm which supports classes quite well.

You don’t realise how messy Javascript is until you work on a large-scale project comprised of more than two developers, ES6 classes come with all of the benefits of pre-existing prototypical inheritance, but require less typing and they make your code easier to understand and resemble closely an object-oriented programming language like Java and its approach to classes.

There really isn’t one reason I can think of to not use ES6 classes even if they are just syntactic sugar. They especially go hand-in-hand with ES6 modules functionality, but that will be for another post.

ES6 classes documentation & references

There are only a few resources out there on ES6 classes with only more to follow, here are a few helpful links to help you master them in your new God ES6 workflow.

An introduction to ES6 classes
Kangax ES6 Compatibility Table
ECMAScript 6 support in Mozilla
Use ECMAScript 6 Today

 

Dwayne

 

13 thoughts on “A Guide To ES6 Classes

  1. >well-structured Javascript that resembles a more realistic programming language

    More realistic? Don’t be silly. You have a good article here, let’s not ruin it by pretending that people’s over-reliance on Java-style OOP makes these classes “more realistic” than prototyped ones. Many of us have used JS style classes without issue, and would argue that baking in such syntactic sugar was less “realistic” and more “caving in to people who didn’t want to learn anything new”. That’s pragmatism, not realism.

  2. You do realise there are plans to to bring additional concepts to the classes functionality most likely in ES7 which will take classes beyond just being syntactic sugar to resembling more realistic traditional programming language classes found in languages like Java? “public” and “private” amongst a few other keywords are reserved keywords in ES6, there has been great discussion on bringing those concepts to classes. By realistic I meant perceived realism, not actual realism as in prototype inheritance takes on a whole new meaning, maybe I wasn’t clear enough in the article.

    Currently classes are definitely purely cosmetic and I realise there are two sides of the debate, the Javascript community is definitely split down the middle as to whether or not Javascript even needed syntactic sugar classes, but we have them and I think it is a good idea that we start using them. They might not be overly different to traditional prototype based inheritance, but if classes are extended in future specifications, then they definitely will go beyond just cosmetic. You can’t deny it arguably looks cleaner and means you have to type less thus saving you time.

  3. Good introduction. It’s important to note though that as “El Goopo” said, classes don’t make a language “realistic”. A lot of languages don’t have classes and are perfectly valid languages, like LISP. What I like about Javascript is it’s ability to write functional-style code, an ability that some of the languages you call “realistic” don’t have, or didn’t have until the latest versions.

    Javascript gives power to the user, beeing so simple you can use it a OO way, or a functional way, or mix them! ES6 adds more than just classes, for people with a traditional OO background this might seem like the biggest thing but IMO it’s just a layer of syntactic sugar. Personally I’m excited for generators, built-in promises and template strings.

    [Here](https://github.com/lukehoban/es6features)’s a nice list of ES6 features 🙂

  4. I work with Javascript as my day job on a medium sized corporate web app. With exactly one (every unusual) exception, I use zero features you are praising. I use no prototypes, no this, no new, no inheritance. My entire codebase is primitive objects/data and functions that operate on those objects. If I need more complex structures, I compose the objects or functions together. I always know what my code is doing and where functionality comes from, unlike the classical languages I grew up on (C++, Java). Because I use generic, often pure functions written in a functional style, and organized into logical components, my code is about as DRY as can be. I’ve even been controversially telling my fellow programmers that inheritance itself is a code smell, in any language. Sure, it has its uses, but so does GOTO.

    That is why I think the classicalization of Javascript is a step in the wrong direction. Typed JS will be benefitial for making certain guarantees to the JIT compiler for speed and memory, but that can be done without classes and inheritance.

  5. @Sanjeet Kumar

    Yes, most definitely. Using Traceur will allow you to write ES6 and convert it to ES5 compatible code. It is however important to keep in mind what browsers you want to support first as this will determine what you can and can’t do.

  6. Clarification: In derived class methods (not constructors), you cannot do `super()` — that’s only for derived constructors. `super()` in methods was removed from ES6. Instead, you have to do `super.foo()`.

  7. I have Javascript link this.

    someClass.js

    class someClass {
    constructor(name, age) {
    this.name = name;
    this.age = age;
    }

    sayName() {
    console.log(this.name);
    }

    sayAge() {
    console.log(this.age);
    }
    }

    var myInstance = new someClass(‘dwayne’, 27);
    myInstance.sayName();
    In cmd:

    node someClass.js
    It’s show dwayne.

    But show I want to use this class in another class like: someClassTest.js How can I call someClass.js for same result

    Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *