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

Dark Mode on website using CSS and JavaScript

In today’s article we are going to learn how to build pretty much standard these days on the web pages and that is the alternative color mode and switching between…

JavaScript: Spread and Rest operators

In today’s article we are going to talk about one of the features of the ES6 version(ECMAScript 2015) of JavaScript which is Spread operator as well as Rest operator. These features…

Javascript: what are callbacks and how to use them.

Today we are going to learn about a concept that is widely used in javascript and that is used quite a lot by today's frameworks, libraries, especially NodeJS. This is…

HTTP Cookies: how they work and how to use them

Today we are going to write about the way to store data in a browser, why websites use cookies and how they work in detail. Continue reading to find out how…

The package managers npm and yarn: main differences

Npm and yarn are package managers that help to manage a project’s dependencies. A dependency is, as it sounds, something that a project depends on, a piece of code that…

The Javascript asign() method to merge and clone objects

In this article, we will be covering Object.assign()method in javascript in detail with examples. A javascript object is a collection of key-value pairs. Keys are also known as properties of object. Keys…

All the javascript functions and methods to manipulate arrays

This article will show that the prominent JavaScript array functions are .map(), .filter(), and .reduce(), and will then go through examples of instances in which .every() and .some() would save…

TypeScript: The evolution of JavaScript

When you're involved in the development of a large project, programming languages like JavaScript don't seem to be the best solution. Their lack of elements such as Language Aids has…

Awesome JavaScript Games and Js Software to create Games

Best sites js13kGames 2019 - Highlights from the js13kGames 2019 competition. js13kGames 2018 - 13 Games in ≤ 13kB of JavaScript. js13kGames 2017 - Build a game in 13kB or less with js13kGames. Adventure Triangle:…

Is JavaScript good for machine learning?

One of the things you always hear when you are talking to someone related to the M.L. world is that, one must learn Python because the vast majority of the…

First steps into JavaScript – a practical guide 3

After we learned the basic ofaccessing DOM elementsandhow to modify them,we are ready for the more exciting parts – handling DOM events. This allows us to make our web way more…

JavaScript: Promises explained with simple real life examples

Handling asynchronous data flows is complex, who hasn't faced codes like this one?: checkWeather('palma de mallorca', (error, weather) => { if (error) throw error; if (weather === 'well') { return checkFlights('palma…

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