ES6 Classes and Inheritance

ES6 Classes and Inheritance

·

2 min read

Classes are defined as the prototype or blueprint which are used to create the objects. Classes have certain methods are variables which are made available to their objects.

Let's understand this with an example; suppose there exists an "Employee" class which has name and experience as input variables, and a method getDetails() which will give the details about the objects which will be created using Employee class.

class Employee {
    // whenever the object of a class is created, the first section of code 
//that run is "constructor".
    // constructor contains the arguments which are passed to objects.
    constructor(givenName, givenExperience) {
        this.name = givenName;
        this.experience = givenExperience;
    }
    getDetails() {
        return `the name of the employee is ${this.name} and working 
experience is ${this.experience} years.`
    }
}

// create an object with employee class.
let employee1 = new Employee("john", 6);
console.log(employee1.getDetails());

// the output of the code snippet is;
// the name of the employee is john and working experience is 6 years.

If you simply console.log(employee1), you will see that it gives us a JS object like object literals.

Inheritance allows us to define a class which has all the methods and properties of its parent class. In ES6, extends is used for inheriting the class. For instance, if there exists a web developer which inherits the Employee class, it will be as follow;

class WebDeveloper extends Employee {
    constructor(givenName, givenExperience, favLanguage) {
        super(givenName, givenExperience);
        this.language = favLanguage
    }
    getDetails() {
        return `the fav language of web developer is ${this.language}.`
    }
}
let john = new WebDeveloper("John", 5, "JavaScript")
console.table(john);
console.log(john.getDetails());

The output of above code will be a table which is formed by JS object;

┌────────────┬──────────────┐
│  (index)   │    Values    │
├────────────┼──────────────┤
│    name'John'    │
│ experience │      5       │
│  language'JavaScript' │
└────────────┴──────────────┘
the fav language of web developer is JavaScript.

If you notice closely, you will see that the getDetails() function which is executed, belongs from the WebDeveloper class. This modification of method in child class is called object overriding. We will talk about object overriding and static methods in classes in later blogs.