Classes

·

5 min read

Classes

JavaScript Classes are templates for JavaScript Objects. Use the keyword class to create a class. A JavaScript class is not an object.

We have to always add a method named constructor() .

Before classes, we used constructor functions to do OOP in JavaScript. Have a look at the example below:

function Person(name, age) {
    this.name = name;
    this.age = age;
}
const p1 = new Person("Mark", "26");
const p2 = new Person("Monty", "21");

Person.prototype.greet = function() {
    console.log(`I am ${this.name} and ${this.age} years old`)
}

console.log(p1);  // Person { name: 'Mark', age: '26' }
console.log(p2);  // Person { name: 'Monty', age: '21' }

p1.greet()  // I am Mark and 26 years old

The Person constructor function has name and age properties. We have to use the new keyword with the Person constructor to create an object person1.

We can also add functions too. To do this we need to add the function into the prototype property of Person. we have added the greet function above. But you can see that it's not that readable compared to OOP concepts we implement in other programming languages.

We can achieve the same using class. The class allows us to write code neatly and it's readable.

class Person {
    constructor(name, age){
        this.name = name;
        this.age = age;  
    }
    greet(){
        console.log(`I am ${this.name} and ${this.age} years old`)
    }
}
const p1 = new Person("Mark", "26");
const p2 = new Person("Monty", "21");

p1.greet()  // I am Mark and 26 years old

Now, the class Person has its properties and functions in one place. The constructor will run only once whenever the object is created.

Getter and Setter methods.

In JavaScript, getter methods are used to access the properties of an object. To create a getter method, the get keyword is used.

In JavaScript, setter methods are used to change the values of an object. To create a setter method, the set keyword is used.

class Person {
    constructor(name, age, language){
        this.name = name;
        this.age = age;  
        this.language = language
    }
    get lang(){
            return this.language
        } 
    set lang(lang) {
        this.language = lang
    }
    greet(){
        console.log(`I am ${this.name} and ${this.age} years old`)
    }
}
const p1 = new Person("Mark", "26", "eng");
const p2 = new Person("Monty", "21");
p2.lang  = "french";

p1.greet() 

console.log(p1.lang)  // eng
console.log(p2.lang)  // french
p1.lang
p1.lang()  // error

Although this is a method, you can not use the () to use it.

Static methods and properties

Static methods are often utility functions, such as functions to create or clone objects, whereas static properties are useful for caches, fixed configuration, or any other data you don't need to be replicated across instances.

class Person {
    constructor(name, age, language){
        this.name = name;
        this.age = age;  
        this.language = language
    }  
    static staticProperty = "value"

    static isEnglish(p) {
        return p.language === "eng"
    }

    static isAdult(age){
        if(age > 18) {
            return "Adult"
        } else {
            return "Not Adult"
        }
    }
}
const p1 = new Person("Mark", "26", "eng");
const p2 = new Person("Monty", "21");
p2.lang  = "french";

console.log(Person.isEnglish(p1))  // true 
console.log(Person.staticProperty)  // value
console.log(Person.isAdult(p2.age))  // Adult 

console.log(p1.staticProperty) // undefined

So, Static methods and properties are only accessible by the class in which it has been specified. If you try to access it with an object of that class, we will face an error.

Inheritance

Inheritance enables you to define a class that takes all the functionality from a parent class and allows you to add more. Using class inheritance, a class can inherit all the methods and properties of another class.

Inheritance is a useful feature that allows code reusability. To use class inheritance, you use the extends keyword.

class Person {
    constructor(name, age){
        this.name = name;
        this.age = age;  
    } 
    greet(){
        console.log(`I am ${this.name} and ${this.age} years old`)
    }
}

class Developer extends Person {
    constructor(name, age, tech){
        super(name, age)
        this.tech = tech
    }

    code(){
        console.log(`I am ${this.name} and I write ${this.tech}`)
    }
}
const p1 = new Person("Mark", "26");
const d1 = new Developer("Monty", "40", "js")

console.log(p1)  // Person { name: 'Mark', age: '26' }
console.log(d1)  // Developer { name: 'Monty', age: '40', tech: 'js' }
console.log(d1.code())  // I am Monty and I write js
console.log(p1.code())  // error

Here, Developer is the child class and the Person is the Parent class. super() keyword is used inside the child class that denotes its parent class. You can not access the child methods using the parent class object just like the last line of code.

Polymorphism

It provides the ability to call the same method on different JavaScript objects. We can write the methods with the same name in parent and child classes.

when we try to access the method on the child object and if the method is not written in the child class, then it will call the same method from the parent class.

class Person {
    constructor(name, age){
        this.name = name;
        this.age = age;  
    } 
    describe(){
        console.log(`Hello, I am a person`)
    }
}

class Developer extends Person {
    constructor(name, age, tech){
        super(name, age)
        this.tech = tech
    }
    describe(){
        console.log(`Hello, I am a person who do coding`)
    }
}
const p1 = new Person("Mark", "26");
const d1 = new Developer("Monty", "40", "js")

console.log(d1.describe()) // Hello, I am a person who do coding

Now, let's remove the describe() method from the child class. As it's not available here, it will check in the parent class Person for the same method and calls it.

class Person {
    constructor(name, age){
        this.name = name;
        this.age = age;  
    } 
    describe(){
        console.log(`Hello, I am a person`)
    }
}

class Developer extends Person {
    constructor(name, age, tech){
        super(name, age)
        this.tech = tech
    }
}
const p1 = new Person("Mark", "26");
const d1 = new Developer("Monty", "40", "js")

console.log(d1.describe())  // Hello, I am a person