Javascript: Introduction to Es6 Classes

by admin admin Date: 26-02-2019 javascript ecmascript es6 oop classes


An exciting new construct that was introduced in the ES6 specification is the ES6 classes. If you're a Javascript developer, you will be aware that Javascript follows prototypal inheritance and sometimes it can get a little messy, with ES6 classes the syntax is simpler and much more intuitive.

However, contrary to what the name may suggest to a developer, classes in ES6 do not translate the object-oriented class-based paradigm typical of other programming languages like Java or Php.
For example, you might notice that Class Keyword in Javascript ES6 does not yet support Private Members; it is always possible to access from outside the methods defined within a given class and modify them at will (or rather by mistake).

JavaScript is therefore an "object" language based on the concept of prototype, unlike most programming languages based on the concept of class. This subtle difference has often caused difficulties for developers accustomed to using languages such as Java or C#, where an object is always an instance of a class. Some libraries implement features that allow you to approach the prototype approach of JavaScript objects to that based on classes of other programming languages, of course with the necessary differences.

Substantial differences between classes and prototypes

In class-based object-oriented programming languages, an object cannot exist unless a class has been defined first. A class is an abstraction that defines the characteristics that objects created by it will have. In JavaScript, however, each object is created directly, without the need to define a class first.

In traditional object languages you can create a subclass from a class and then objects that inherit the characteristics of the base class. In JavaScript it is possible to obtain an analogous effect through the concept of prototype, with which an object takes to model another object sharing its characteristics and eventually adding new ones.

Unlike traditional class-based object-oriented languages, where a class defines all the characteristics that an object can have, in JavaScript you can define some characteristics for an object and enrich it with new properties and methods at runtime.
Let's start with our first javascript class code

Creating Classes in JavaScript (Ecma 6)

A class in this syntactical model is an alternative way to define a manufacturer. We can for example Use the class keyword to create a class and define the constructor of the Vehicle object in the following way:

class Vehicle {
    constructor(brand, model) {
        this.brand = brand;
        this.model = model;
        this.kind= "";
        this._engine = "";        
    }
}

The syntax is familiar to a OOP developer but still note that the constructor is indicated by the constructor() method that contains the arguments about the vehicle, we can set their properties using the this

Note that, as we said before, ES6 did not introduce real classes but rather a syntactic fiction, as we can easily demonstrate by simply querying the Browser Console about the code just written:

> typeof Vehicle 
"function"

We can create a new object from the class just defined by the new operator, in a completely identical way to what we did with the functionally defined constructor:

let vehicle = new Vehicle("Ferrari", "Testarossa");

Properties and methods, getters and setters

You can create properties, methods, getters and setters quite intuitively as shown by the following code:

class Vehicle {
    constructor(brand, model) {
        this.brand = brand
        this.model = model
        this.kind= "";
        this._engine = "";    
    }
    showVehicleBrandModel() {
        return this.brand + " " + this.model;
    }
    get engine() { return this._engine; }
    set engine(value) {
        this._engine = value;        
    }
}

Here we define a showVehicleBrandModel() method and the two get engine() and set engine(value), then we show in console.log the call of method showVehicleBrandModel(). Note that we use _engine as property because the engine will be used with get and set functions

let vehicle = new Vehicle("Ford", "Mustang");
// Get the description
console.log(vehicle.showVehicleBrandModel());
> 'Ford Mustang'

vehicle.engine = 'V6'
console.log(vehicle.engine);
>'V6'

We can call the method vehicle.showVehicleBrandModel() after we have created a new instance of Vehicle. Also we can se property vehicle.kind as usual.

Is it also possible to add properties and methods on the fly. For example we can add the weight property dinamically

vehicle.weight = 1400;
console.log(vehicle.weight);
> 1400;

Clearly, if we create a new instance of Vehicle, we lose all the dynamic properties inserted before.

 

Static methods

Like other languages with static class members, the static keyword will create a method associated with the class, and not with an instance of the class. In other words, you can only reach a static method using the name of the class.

class Vehicle {
    constructor(brand, model) {
        this.brand = brand
        this.model = model
        this.kind= "";
        this._engine = "";    
    }
    showVehicleBrandModel() {
        return this.brand + " " + this.model;
    }
    static ignite(){
        console.log("wrooom")
     }
    // more code ...
}
console.log(Vehicle.ignite());
> 'wrooom.'

Since these methods operate on the class instead of instances of the class, they are called on the class, is not necessary to define a new Vehicle to call the static method.

 

Inheritance

In object-oriented programming, inheritance is the mechanism of basing a class upon another class, retaining similar implementation. Also defined as deriving new classes (sub classes) from existing ones (super class or base class) and forming them into a hierarchy of classes. :

class Vehicle {
    constructor(brand, model) {
        this.brand = brand
        this.model = model
        this.kind= "";
        this._engine = "";    
    }
    showVehicleBrandModel() {
        return this.brand + " " + this.model;
    }
    static ignite(){
        console.log("wrooom")
     }
}
class DetailedVehicle extends Vehicle {
    showVehicleBrandModel() {
        return "Brand:" + this.brand + " - Model:" + this.model;
    }
}

let vehicle = new Vehicle("Ford", "Mustang");
let vehicleDetail = new DetailedVehicle("Ford", "Mustang");
console.log(vehicle.showVehicleBrandModel());
> 'Ford Mustang'
console.log(vehicleDetail.showVehicleBrandModel());
> 'Brand:Ford - Model:Mustang'
    

In this case we create a new class vehicleDetail that has the same propertis of Vehicle.

Thanks to the extends keyword you can specialize a class into a child class while keeping reference to the root class. With all these great additions, it is now possible to create classes and work with inheritance without dealing with prototype, in our case we overwrite the showVehicleBrandModel() method.

 

The Super Keyword

If we need to get values of a parent class method or property we can use the super keyword:

class Vehicle {
    constructor(brand, model) {
        this.brand = brand
        this.model = model
        this.kind= "";
        this.engine = "";    
    }
    otherProperties(){
        this.kind= "car";
        this.engine = "v6";  
        return "this " + this.kind + " with engine " + this.engine + " it's very fast";
    }
    showVehicleBrandModel() {
        return this.brand + " " + this.model;
    }
}

class DetailedVehicle extends Vehicle {
    showVehicleBrandModel() {         
        return this.brand + " " + this.model + " " + super.otherProperties();
    }
}

let vehicleDetail = new DetailedVehicle("Ford", "Mustang");
console.log(vehicleDetail.showVehicleBrandModel());
 
> Ford Mustang this car with engine v6 it's very fast
    

Here we are calling the otherProperties() method contained in Vehicle class and inject it to the new redefined showVehicleBrandModel() of vehicleDetail class. Note that if we call the static method we get an error.

 

Final considerations

If you have used OOP Classes in other languages, you will be familiar with this concept of classes in Javascript ES6, functionalities like static methods and inheritance are really similar to other programming languages..

This covers all the major functionality of classes, anyway I suggest you expand the topic by searching in our site with the keywords javascript and ES6

 

 
by admin admin Date: 26-02-2019 javascript ecmascript es6 oop classes hits : 2916  
 
 
 
 

Related Posts