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 : 7584  
 
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

How to upload files to the server using JavaScript

In this tutorial we are going to see how you can upload files to a server using Node.js using JavaScript, which is very common. For example, you might want to…

How to combine multiple objects in JavaScript

In JavaScript you can merge multiple objects in a variety of ways. The most commonly used methods are the spread operator ... and the Object.assign() function.   How to copy objects with…

The Payment Request API: Revolutionizing Online Payments (Part 2)

In the first part of this series, we explored the fundamentals of the Payment Request API and how it simplifies the payment experience. Now, let's delve deeper into advanced features…

The Payment Request API: Revolutionizing Online Payments (Part 1)

The Payment Request API has emerged as the new standard for online payments, transforming the way transactions are conducted on the internet. In this two-part series, we will delve into…

Let's create a Color Picker from scratch with HTML5 Canvas, Javascript and CSS3

HTML5 Canvas is a technology that allows developers to generate real-time graphics and animations using JavaScript. It provides a blank canvas on which graphical elements, such as lines, shapes, images…

How do you stop JavaScript execution for a while: sleep()

A sleep()function is a function that allows you to stop the execution of code for a certain amount of time. Using a function similar to this can be interesting for…

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…

Clicky