Using the New Class Syntax in JavaScript

in #technology9 years ago

ECMAScript 2015 (ES6) has specified a new syntax for defining classes in JavaScript. Of course, this does not change the basic inheritance pattern in JavaScript, which is prototype-based inheritance. It just provides a syntactical sugar for class definition.

Classes can be defined using class declarations or class expressions. Class declarations have an important difference with function declarations, in that they do not cause hoisting. This means that any class declaration must come before actually using that class.

Here is an example of class declarations:

    class Shape {
        constructor() {}
    }

    class Rectangle extends Shape {
        constructor(width, height) {
            super();
            this.width = width;
            this.height = height;
        }
        area() {
            return this.width * this.height;
        }
    }

    class Square extends Rectangle {
        constructor(side) {
            super(side, side);
        }
    }

    let square = new Square(15);

    console.log(square.area()); // prints 225

This works in NodeJS and modern browsers. In Nashorn, however, even when the new ES6 flag is enabled (with JDK 9), the following error is thrown:

    ES6 class declarations and expressions are not yet implemented

It appears that for using the new class syntax in Nashorn, we must still wait for a future update.

Coin Marketplace

STEEM 0.05
TRX 0.33
JST 0.078
BTC 63144.83
ETH 1685.61
USDT 1.00
SBD 0.39