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 : 7067  
 
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 AND DEVELOPMENT.

 
 
 

Related Posts

Mastering array sorting in JavaScript: a guide to the sort() function

In this article, I will explain the usage and potential of the sort() function in JavaScript.   What does the sort() function do?   The sort() function allows you to sort the elements of…

Infinite scrolling with native JavaScript using the Fetch API

I have long wanted to talk about how infinite scroll functionality can be implemented in a list of items that might be on any Web page. Infinite scroll is a technique…

Sorting elements with SortableJS and storing them in localStorage

SortableJS is a JavaScript extension that you will be able to use in your developments to offer your users the possibility to drag and drop elements in order to change…

What is a JWT token and how does it work?

JWT tokens are a standard used to create application access tokens, enabling user authentication in web applications. Specifically, it follows the RFC 7519 standard. What is a JWT token A JWT token…

Template Literals in JavaScript

Template literals, also known as template literals, appeared in JavaScript in its ES6 version, providing a new method of declaring strings using inverted quotes, offering several new and improved possibilities. About…

How to use the endsWith method in JavaScript

In this short tutorial, we are going to see what the endsWith method, introduced in JavaScript ES6, is and how it is used with strings in JavaScript. The endsWith method is…

What are javascript symbols and how can they help you?

Symbols are a new primitive value introduced by ES6. Their purpose is to provide us unique identifiers. In this article, we tell you how they work, in which way they…

Callbacks in JavaScript

Callback functions are the same old JavaScript functions. They have no special syntax, as they are simply functions that are passed as an argument to another function. The function that receives…

How to create PDF with JavaScript and jsPDF

Creating dynamic PDF files directly in the browser is possible thanks to the jsPDF JavaScript library. In the last part of this article we have prepared a practical tutorial where I…

How to make your own custom cursor for your website

When I started browsing different and original websites to learn from them, one of the first things that caught my attention was that some of them had their own cursors,…

PHP - The Singleton Pattern

The Singleton Pattern is one of the GoF (Gang of Four) Patterns. This particular pattern provides a method for limiting the number of instances of an object to just one.…

Node.js and npm: introductory tutorial

In this tutorial we will see how to install and use both Node.js and the npm package manager. In addition, we will also create a small sample application. If you…