Understanding ECMAScript 6: Class and Inheritance
I’d like to share with you a series of articles about ECMAScript 6, sharing my passion for it and explaining how it can work for you. I hope you enjoy reading them as much as I did writing them.
First, I work in Microsoft on the browser rendering engine for Project Spartan, which is a vast improvement over the Internet Explorer engine we got to know (and love?) over the years. My personal favorite feature of it is that it supports a lot of ECMAScript 6. To me, this is a massive benefit to writing large applications for the web.
We now have almost 70% of ECMAScript 6 features in Project Spartan so far according to http://kangax.github.io/compat-table/es6/ and ES6 on status.modern.IE.
I love JavaScript, but when it comes to working on large projects like Babylon.js, I prefer TypeScript which is now powering Angular 2 btw. The reason is that JavaScript (or otherwise known as ECMAScript 5) doesn’t have all the syntax features I am used to from other languages I write large projects in. I miss classes and inheritance, for instance.
So without further ado, let’s get into just that:
Creating a class
JavaScript is a prototype oriented language and it is possible to simulate classes and inheritance with ECMAScript 5. The flexibility of functions in JavaScript allows us to simulate encapsulation we are used to when dealing with classes. The trick we can use for that is to extend the prototype of an object:var Animal = (function () {
function Animal(name) {
this.name = name;
}
// Methods
Animal.prototype.doSomething = function () {
console.log("I'm a " + this.name);
};
return Animal;
})();
var lion = new Animal("Lion");
lion.doSomething();
We can see here that we defined a “class” with “properties” and “methods”.
The constructor is defined by the function itself (function Animal) where we can instantiate properties. By using the prototype we can define functions that will be considered like instance methods.
This works, but it assumes you know about prototypical inheritance and for someone coming from a class-based language it looks very confusing. Weirdly enough, JavaScript has a class keyword, but it doesn’t do anything. ECMAScript 6 now makes this work and allows for shorter code:
class AnimalES6 {
constructor(name) {
this.name = name;
}
doSomething() {
console.log("I'm a " + this.name);
}
}
var lionES6 = new AnimalES6("Lion");
lionES6.doSomething();
The result is the same, but this is easier to write and read for developers who are used to writing classes. There is no need for the prototype and you can use the “constructor” keyword to define the constructor.
Furthermore, classes introduce a number of new semantics that aren’t present in the ECMAScript 5 equivalent. For example, you cannot call a constructor without new or you cannot attempt to construct methods with new. Another change is that methods are non-enumerable.
Interesting point here: Both versions can live side by side.
At the end of the day, even with the new keywords you end up with a function with a prototype where a function was added. A “method” here is simply a function property on your object.
One other core feature of class based development, getters and setters, are also supported in ES6. This makes it much more obvious what a method is supposed to do:
class AnimalES6 {
constructor(name) {
this.name = name;
this._age = 0;
}
get age() {
return this._age;
}
set age(value) {
if (value < 0) {
console.log("We do not support undead animals");
}
this._age = value;
}
doSomething() {
console.log("I'm a " + this.name);
}
}
var lionES6 = new AnimalES6("Lion");
lionES6.doSomething();
lionES6.age = 5;
Pretty handy, right?
But we can see here a common caveat of JavaScript: the “not really private” private member (_age). I wrote an article sometimes ago on this topic.
Thankfully, we now have a better way to do this with a new feature of ECMAScript 6: symbols:
var ageSymbol = Symbol();
class AnimalES6 {
constructor(name) {
this.name = name;
this[ageSymbol] = 0;
}
get age() {
return this[ageSymbol];
}
set age(value) {
if (value < 0) {
console.log("We do not support undead animals");
}
this[ageSymbol] = value;
}
doSomething() {
console.log("I'm a " + this.name);
}
}
var lionES6 = new AnimalES6("Lion");
lionES6.doSomething();
lionES6.age = 5;
So what’s a symbol? This is a unique and immutable data type that could be used as an identifier for object properties. If you don’t have the symbol, you cannot access the property.
This leads to a more “private” member access.
Or, at least, less easily accessible. Symbols are useful for the uniqueness of the name, but uniqueness doesn’t imply privacy. Uniqueness just means that if you need a key that must not conflict with any other key, create a new symbol.
But this is not really private yet because thanks to Object.getOwnPropertySymbols, downstream consumers can access your symbol properties.
Handling inheritance
Once we have classes, we also want to have inheritance. It is – once again – possible to simulate inheritance in ES5, but it was pretty complex to do. For instance, here what is produced by TypeScript to simulate inheritance:var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var SwitchBooleanAction = (function (_super) {
__extends(SwitchBooleanAction, _super);
function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
_super.call(this, triggerOptions, condition);
this.propertyPath = propertyPath;
this._target = target;
}
SwitchBooleanAction.prototype.execute = function () {
this._target[this._property] = !this._target[this._property];
};
return SwitchBooleanAction;
})(BABYLON.Action);
Not really easy to read.
But the ECMAScript 6 alternative is better:
var legsCountSymbol = Symbol();
class InsectES6 extends AnimalES6 {
constructor(name) {
super(name);
this[legsCountSymbol] = 0;
}
get legsCount() {
return this[legsCountSymbol];
}
set legsCount(value) {
if (value < 0) {
console.log("We do not support nether or interstellar insects");
}
this[legsCountSymbol] = value;
}
doSomething() {
super.doSomething();
console.log("And I have " + this[legsCountSymbol] + " legs!");
}
}
var spiderES6 = new InsectES6("Spider");
spiderES6.legsCount = 8;
spiderES6.doSomething();
Thanks to the “extends” keyword you can specialize a class into a child class while keeping reference to the root class with the “super” keyword.
With all these great additions, it is now possible to create classes and work with inheritance without dealing with prototype voodoo magic.
Why using TypeScript is even more relevant than before…
With all these new features being available on our browsers, I think it is even more relevant to use TypeScript to generate JavaScript code.
First off, all the latest version of TypeScript (1.4) started adding support for ECMAScript 6 code (with let and const keywords) so you just have to keep your existing TypeScript code and enable this new option to start generating ECMAScript 6 code.
But if you look closely at some TypeScript you will find that this looks like ECMAScript 6 without the types. So learning TypeScript today is a great way to understand ECMAScript 6 tomorrow!
Is there a reason why you use “var” and not “let” in your examples?
Just a quick note that TypeScript’s classes are incompatible with ES6 classes. It isn’t spec-compliant like Babel’s.
So the classes you use in TypeScript will result in breaking changes switching to native ones.