ES6 – ECMAScript 6: Classes and Inheritance

1

ES6: Hereby I would like to invite you to a series of articles about ECMAScript 6. With which I not only share my enthusiasm. But above all explain how to best use ES6. I hope you enjoy reading at least as much as I did writing.

For my background. I work at Microsoft on the browser rendering engine for the Microsoft Edge. Which is a huge step forward compared to the previous Internet Explorer engine. Which we have learned extensively over the years (and love?). My personal favorite feature is that it supports loads of ECMAScript 6. This greatly facilitates the writing of complex web applications.

According to http://kangax.github.io/compat-table/es6/ and ES6 on dev.modern.ie/platform/status, we currently have nearly 70% of the ECMAScript 6 features in Microsoft Edge.

No question, I like to work with JavaScript, but when I’m working on big projects like Babylon.js. I prefer to use TypeScript, which also drives Angular 2. The reason is that in JavaScript (also known as ECMAScript 5) I miss some syntax functions that other programming languages ​​I use to write big projects with. For example, I miss classes and inheritances.

To learn how to switch from JavaScript to TypeScript, read this article. For a detailed introduction to TypeScript, visit this free online Microsoft Virtual Academy (MVA) course. Download the free download of TypeScript 1.4 for Visual Studio 2013 here.

Create a class

JavaScript is a prototype-based language and with ECMAScript 5 you can simulate classes and inheritance. You want to improve the performance of your web application? Here are some handy tips for improving your HTML / JavaScript code.

JavaScript’s flexible features allow us to simulate data encapsulation as if we were working with classes. To achieve this, we 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();

It becomes clear here that we have defined a ” class ” with ” properties ” and ” methods “.

The constructor is defined by the function itself (function Animal). This allows us to instantiate properties. By using the prototype, we can define functions that are treated like instance methods.

So you can do it that way, but you have to understand some of the prototypical inheritance. And anyone who is used to class-based languages ​​will find it all a bit confusing. Of course, it’s also strange that the keyword class exists in JavaScript, but it does not do anything. ECMAScript 6, on the other hand, gets it up and running, with a simpler code:

class AnimalES6 {
    constructor(name) {
        this.name = name;
    }

    doSomething() {
        console.log("I'm a " + this.name);
    }
}

var lionES6 = new AnimalES6("Lion");
lionES6.doSomething();

In the end we have the same result. But for developers accustomed to working with classes, it’s far easier to write and read. A prototype is not needed here and you simply use the keyword “constructor” to define the constructor.

In addition, classes bring a lot of new semantics, which was not present in ECMAScript 5. So a constructor can not be called without the keyword “new” or methods constructed with “new”. Another change: methods are not enumerable.

Interestingly, both versions can be used in parallel.

Because despite the new keywords, at the end of the day we end up with a feature with a prototype to which a feature has been added. A “method” here simply denotes a functional property of the object.

Another core function of class-based development, getter and setter, is also supported by ES6. This quickly reveals what the purpose of methods is and what they should 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;

Very handy, right?

At the same time one of the typical reservations about JavaScript comes to the fore: the not so confidential “private member” ( _age ). More on this topic I wrote in this article.

With a new feature of ECMAScript 6, we now have a more elegant way to do it, using “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 is a symbol in this context? It is a unique, immutable data type that allows you to define unique object properties. Without the symbol there is no access to the properties.

The result is a “more personal” access to the members. Or at least this access is not that easy anymore. Symbols help with the uniqueness of names, but this uniqueness alone does not guarantee privacy. It just means: If a key is needed that is not allowed to collide with another one, create a new symbol.

That nobody is so “private” here is due to Object.getOwnPropertySymbols . This allows others to access the symbol properties.

Work with heredity

Once we have classes, we also expect inheritance possibilities. Again, it was already possible to simulate inheritance in ES5, but it was quite a complex matter.

For example, if TypeScript mimicked 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 necessarily very easy to read, right? The alternative of ECMAScript 6 – ES 6 looks 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();

The word “extends” can be used to derive classes from another, ie to create specialized classes (“child”). The keyword “super” then establishes the relationship with the base class.

Thanks to all these new features, we can now create classes and work with inheritances without having to get help at Hogwarts to do the same with prototypes.

Why TypeScript is even more relevant than before …

Now that we have the described new features in our browser, i think it makes even more sense than before to use TypeScript to create JavaScript code.

Finally, TypeScript (1.4) now supports ECMAScript 6 code (with let and const keywords). So existing TypeScript code can still be used, you just have to activate this new option to create ECMAScript 6 code.

And if you take a closer look at a few lines of TypeScript, you will notice that they look like ECMAScript 6 without the types. Anyone who masters TypeScript today will understand ECMAScript 6 faster tomorrow.

In this issue of TechTalk, Daniel Meixner and Chris Heilmann talk extensively about what’s new in Edge, ECMAScript 2015 and TypeScript.

Conclusion

Who works with TypeScript, can use the functions in all browsers, the code is converted into ECMAScript 5. If you want to use ECMAScript 6 directly in the browser, you must upgrade to Windows 10. And test the rendering engine of Microsoft Edge there. But if that’s too much work, just because he just wants to see the new browser functions. Remote.modern.ie provides access to a Windows 10 computer with Microsoft Edge. This also works with MacOS or Linux machines.

Sure, Microsoft Edge is not the only browser that supports the open standard ES6. How far the support of other browsers reaches is listed here: http://kangax.github.io/compat-table/es6/

And to be euphoric again: I think the future prospects for JavaScript with ECMAScript 6 are really brilliant. And I can not wait for it to be supported by as many browsers as possible.

This article is part of the Web Dev Tech Series by Microsoft. We’re excited to share Microsoft Edge and its new EdgeHTML rendering engine with you. Free virtual machines or remote testing for Mac, iOS, Android or Windows can be found here: dev.modern.IE.

Source: https://www.drweb.de/ecmascript-6-besser-verstehen-klassen-und-vererbung-58622/

For more information – ECMAScript 6 – ES6

Share This:

1 Comment

  1. Pingback: ES6 – ECMAScript 6: Classes and Inheritance – FrontNet – Javascript World

Leave A Reply

Powered by FrontNet