All You Need to Know About Classes in ES6

ES6 introduces a classkeyword. Other programming languages like Java, C# has class concepts for long time. The purpose of classkeyword is same in JavaScript6. It creates a class definition. A class is a blue print which can be used to instantiate objects.

How class concept is created in older JavaScript versions

In Javascript version before ES6, we first create a constructor function. The constructor function is then extended with a property or method so that all generated objects have those.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// This is a constructor function
var Person = function (name) {
    this.name = name;
};
// Extending the constructor function
Person.prototype.showName = function () {
    console.log("My name is " + this.name);
};
// Creating 2 objects
var obj1 = newPerson("Joby");
var obj2 = newPerson("Joseph");
// Accessing methods
obj1.showName(); // "My name is Joby"
obj2.showName(); // "My name is Joseph"

So we could do things which a class can do before ES6. Only problem is that it does not look straight forward for a developer who comes from a Java or C# background.

Rewriting Classes in ES6 way

The same code above can be written in a more clean way in ES6. We are going to use classkeyword.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Person {
    constructor (name) {
        this.name = name;
    }
    showName() {
        console.log("My name is " + this.name);
    }
};
// Creating 2 objects
var obj1 = newPerson("Joby");
var obj2 = newPerson("Joseph");
// Accessing methods
obj1.showName(); // "My name is Joby"
obj2.showName(); // "My name is Joseph"

Behind the scene the JavaScript runtime is converting everything to ES5 way and running it. But the code is much cleaner.

In the example above showName()is a method defined inside Personclass. We do not have to add a function keyword before the method definition.

Constructor function

constructor is the keyword used inside a class to define a constructor function. Like in other languages, a constructor function is executed each time an object is created.

Get and Set in ES6 class

getand setis used to read and write object properties respectively. Consider following code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Person {
    constructor (name) {
        this._name = name;
    }
    
    get name(){
        returnthis._name;
    }
    
    set name(newName){
        this._name = newName;
    }
};
var obj = newPerson("Joby");
// set
obj.name = "NewJoby";
// get
console.log(obj.name); // "NewJoby"

getcreates a readable property for an object. In above example the readable property is name. Even though inside the class we define get variable like a function, we are not using it using function call syntax. We simply use obj.nameinstead of obj.name().

In the similar manner setaccepts a parameter for new value to be set. In the example above, the getand setread and write to _name. The code is pretty straight forward. But you can make it more complex. See example below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Person {
    constructor (name) {
        this._name = name;
    }
    
    get toGetName(){
        returnthis._name.toUpperCase();
    }
    
    set toSetName(newName){
        this._name = newName + " is good";
    }
};
var obj = newPerson("Joby");
// calling setter
obj.toSetName = "NewJoby";
// calling getter
console.log(obj.toGetName); // "NEWJOBY IS GOOD"

You can make a read only variable by using only get. You can make a write only variable by using only set. We can implement encapsulation effectively using getand set.

Inheritance in ES6 using classes

As in any classical OOP language, in ES6 a class can inherit from another class. We can do inheritance before ES6 versions by various techniques. But ES6 standardizes syntax.

So here is my parent class.

1
2
3
4
5
class Vehicle {
    constructor(modelName) {
        this.modelName = modelName;
    }
}

The parent class Vehicle has only one property. Next we are going to create a child class Car.

1
2
3
4
5
class Car extends Vehicle {
    show() {
        console.log(`${this.modelName} is amazing`);
    }
}

Car now has one property(name) and one method(show); Next we create a Car object.

1
2
varobj = newCar('BMW');
obj.show(); // "BMW is amazing"

In the example above Person is the super class.

How to add a new property to child class?

In the example above Vehicleclass contained a property modelName. So it is inherited by Carclass. What if I need to add a new property to child class?
See how I updated the child(Car) class.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Car extends Vehicle {
    constructor(modelName, category){
        super(modelName);
        this.category = category;
    }
    show() {
        console.log(`${this.modelName} is amazing ${this.category} car.`);
    }
}
var obj = newCar('Ferrari', 'racing'); // "Ferrari is amazing racing car."
obj.show();

supermethod calls the parent constructor.

Also you need to note that if a child class has defined a constructor explicitly, then the parent constructor is not called.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *