Javascript: Introduction to ES6 classes

Javascript: Introduction to ES6 classes
by Janeth Kent 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 Janeth Kent Date: 26-02-2019 javascript ecmascript es6 oop classes hits : 5187  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN END DEVELOPMENT.

 
 
 

Related Posts

Difference between arrow and normal functions in JavaScript

In this tutorial we are going to see how arrow functions differ from normal JavaScript functions. We will also see when you should use one and when you should use…

JavaScript Arrow functions: What they are and how to use them

In this article we are going to see what they are and how to use JavaScript Arrow Functions, a new feature introduced with the ES6 standard (ECMAScript 6). What are Arrow…

How to insert an element into an array with JavaScript

In this brief tutorial you will learn how to insert one or more elements into an array with JavaScript. For this we will use the splice function. The splice function will not…

What is the difference between primitives types and objects in JavaScript?

In this short tutorial we are going to look at the differences between primitive types and objects in JavaScript. To start with, we're going to look at what primitive types…

How to get DOM elements with JavaScript

When you access any element of the DOM, it is usual to save it in a variable. This is something that at first might seem very simple, but if you…

How to reverse an array in JavaScript

In this tutorial we are going to see how you can change the order of the elements of an array so that they are inverted. You could use a loop…

How synchronize the scroll of two divs with JavaScript

In case you have two divs of different sizes you may sometimes want to scroll both at the same time but at different speeds depending on their size. For example,…

How to use the codePointAt method in JavaScript

The JavaScript codePointAt method has more or less the same function as the charCodeAt method, used to get the 16-bit Unicode representation of the character at a certain position in…

How to check if a value is a number in JavaScript

In this short tutorial we are going to look at the various methods that exist to find out if a value is a number in JavaScript.   1. Using the isNaN() function   One…

How to use the charCodeAt method in JavaScript

The charCodeAt method is accepted by strings in JavaScript, returning the 16-bit Unicode code of the character at the position we pass as a parameter to the method. The charCodeAt method…

How to use the charAt method in JavaScript

The charAt method is accepted by strings in JavaScript, returning the position of the character passed as a parameter within the string. If the string contains multiple occurrences of the character…

Strings in JavaScript: What they are and how to use them

In this tutorial we are going to explain what strings are and how they are used in JavaScript. The tutorial is intended for people who are learning to program in…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration