ES6 Sampler #3 : Classes

October 05, 2016


JavaScript

Preface

This is the third in a series of posts where I explore all the new stuff es6 has to offer, come along and learn about classes.

Pssst... You might also want to check the first 2 in the series:
Note - Challenges: I gave myself little challenges you are welcome to try if you want to recreate my own learning curve.

Let's start:

ECMAScript 6 introduces the class syntax, I suppose the first thing we would need to figure out is what does it replace or it’s equivalent in es5, so.

Challenge: Find out what a class does and the equivalent in es5

See the Pen ES6 Sampler- Classes pt1 by Eugenio - Keno - Leon (@k3no) on CodePen.

In a nutshell, if you already know about prototypes you alaready know how a class works, it is basically syntactical sugar (a more readable or convenient way) to deal with objects and inheritance.

How many ways ?

This being a programming language, there is nunance and variation when defining a class, so..

Challenge: Figure out the different ways of defining a class in es6

See the Pen ES6 Sampler- Classes pt2 by Eugenio - Keno - Leon (@k3no) on CodePen.

Class Methods

A lot of what makes an object useful is the internal machinery as I like to call it or Methods as most people do, let’s figure out how to make some methods with es6 classes:

Challenge: Find out how methods work with es6 classes

See the Pen ES6 Sampler- Classes pt3 by Eugenio - Keno - Leon (@k3no) on CodePen.

Extending Classes

Another handy thing one can do with classes is extending them so they add or change behaviour from a base class (or prototype) , let’s try that:

Challenge: Find out how to extend a class in es6

See the Pen ES6 Sampler- Classes pt4 by Eugenio - Keno - Leon (@k3no) on CodePen.

Calling super

One last things we must investigate, is how does one refer to the original class within an extended class?

Challenge: Find out how to use super in es6

See the Pen ES6 Sampler- Classes pt5 by Eugenio - Keno - Leon (@k3no) on CodePen.

And that’s it, a quick overview of what classes bring to Javascript; One last thing I would like to start doing, is leaving a final challenge, one you might encounter on a coding test, so let’s try that:

Coding Test: Create a class with at least 2 methods, extend it and use super to call one of the methods.

Extra Credit: Create the same functionality in es5.

See the Pen ES6 Sampler- Classes pt6 by Eugenio - Keno - Leon (@k3no) on CodePen.

Conclusion

Classes in es6 while being syntactic sugar, are a welcome adition if you considered protoype chaining and inheritance a bit cumbersome, what’s more, it aligns javascript with other languages that use classes.

TL;DR:

Classes in es6 = delicious prototype/inheritance sugar

Best,

Keno.