ES6: JS's Prototype-based inheritance and classes demystified
October 15, 2015
JavaScript classes are introduced in ECMAScript 6 and are syntactical sugar over JavaScript’s existing prototype-based inheritance.
Note: The class syntax is not introducing a new object-oriented inheritance model to JavaScript, so what is happening behind all this new sugar? Let’s digg how ES6 classes works compared to the pseudcoclassical subclass pattern we are used to work with within ES5.
Prototype-based inheritance in ECMAScript 5
Let’s immagine a simple scenario, where we have a Car class. We want the constructor function to decorate each generated instance, for example by adding a brand property to the car. We also want each instanciated object to have access to some class methods, for example a horn() function.
Now, let’s add a subClass and let’s call it Tesla (being it a truly new type of car, and therefore a subClass of Car). Of course, we want each Tesla to be branded ‘tesla’ as well, but we also want it to have some unique features, like for example the ludicrousSpeed function.
Without all the comments the Tesla subclass constructor should look something like:
Running some tests, to make sure that everything works as expected:
Classes in ECMAScript 6, or better, Sugar over the ES5 prototype-based inheritance
Now that we did brush up on the pseudoClassical subclass pattern, let see how the previous code will look like in ES6, using the new Class Syntactic sugar. Refer to the code above to better understand what is going on under the hood, it should be pretty self explanatory by now.
Running some tests, to make sure that everything works as expected:
To run and test ES6 code on chrome make sure you switch on the harmony setting. To do so, just enter in your chrome address bar the folloing url: chrome://flags/#enable-javascript-harmony.
Note class and super are not yet supported in chrome, therefore you won’t be able to fully test this ES6 out of the box. I strongly encourage you to use the babel transpiler, or play with its online REPL