Level: Intermediate to Advanced.
Part 3 – Introducing Classes
The prototypical inheritance model is more powerful than class-based inheritance model. Further, you can use prototypical inheritance to recreate a sort of class-based inheritance model. If you’re trying to inherit and share “methods” among objects, your inherited function acts like just another property that was cloned to the new object. The “this” in the cloned function will point to the new cloned object and not the object it was cloned from. Developers experienced with Java and C++ will certainly be confused by this point and if you’re unaware of this major difference in programming paradigm, you will certainly write buggy code.
ES2015 adds syntactical sugar to make it easier for developers used to class-based object inheritance pattern.
Introducing Classes Syntactical Sugar
Classes are in fact just functions. You can declare a class, just like functions, using declarations and expressions.
ES2015 also introduces the constructor keyword. This is a special function used to initialize an object created with a class. If you don’t define your own constructor, there are default constructors that do nothing or pass arguments to the parent constructor (see next paragraph).
ES2015 also introduces the extends and super keywords. Extends is used to tell an object to inherit from another object, forming a parent-child relationship. Super is used to call a function in the parent object from the child object (if there is indeed a parent). Notice how calling the parent constructor differs from called a parent function.
Finally, one more keyword was introduced in ES2015 and that is the static keyword. The static keyword allows you defined a static function that can be called without creating a new instance of the object. It is also not callable from the class when it is instantiated. You can mostly use this keyword to create utility functions.
The new keywords introduced in ES2015 make it easier for developers to recreate some of the programming patterns from other languages like C#, Java or C++. You do have to remember though that these new keywords are only syntactical sugar meant to make development easier but do not change the underlying prototypical inheritance model. Don’t forget that!
In the next parts of this tutorial series, I will be discussing different language features such as generators & iterators, block scoping, arrows, and more. I will also be sharing strategies for how best to manage a transition to ES6 either through transcompilation or using shims for different features. Stay tuned for the next edition!
Missed the Previous Parts?
You can read the previous parts here: