Complete Object Oriented Programming (OOP) in Javascript

Complete Object Oriented Programming (OOP) in Javascript

All you need to know about object oriented programming in javascript

ยท

5 min read

Object oriented programming is a critical aspect of javascript that is relatively difficult to comprehend due to its complicated syntax. This blog will explain all the important concepts of object oriented programming.

What is Object oriented programming ?

Object oriented programming is a style of programming implemented with classes and objects. In OOP, classes - a design of all the properties and functions - can be created. Take, for instance, a car company creating multiple cars. We can create a class called car. This class can have properties (such as color and top speed) along with functions (such as drive, brake, play music).

So, in a nutshell, classes can define properties and functions relevant to it.

Defining a class in javascript

Let us create a class called car in javascript

class Car {

}

It is convention to capitalize a class in object oriented programming.

Constructor

For the car to take in certain parameters (such as color and top speed), we must use the constructor function. The constructor is called only once: when the class is created.

class Car {
    constructor(_model, _color, _top_speed){
        this.model = _model;
        this.color = _color;
        this.top_speed = _top_speed;
    }
}

The 'this' object can be accessed all around the class. So by setting values in the 'this' object, we can access all the input parameters.

Now you can call this class and create a car. The 'new' keyword must be used when creating a new class

const tesla = new Car("Model S", "black", 200);

In the class, the model, color and top speed are now available to use as variables to perform any operation

Getters and Setters

A value can be retrieved using the get keyword

class Car {
    constructor(_model, _color, _top_speed){
        this.model = _model;
        this.color = _color;
        this.top_speed = _top_speed;
    }

    get recommended_speed () {
        return this.top_speed * 0.75;
    }
}

Now to get the recommended speed, it can be called similar to how a property is accessed

const tesla = new Car("Model S", "black", 200);
const recommendedSpeed = tesla.recommended_speed;

With the get keyword, you do not need to add any parentheses as you are not calling a function. A getter cannot accept any parameters. If you want to pass a variable, you must remove the get keyword to make recommended_speed a function. Then, a pair of parentheses can be added.

With the set keyword, you can assign a certain property a value. Let us create a setter for setting the top speed upon changing the recommended speed

class Car {
    constructor(_model, _color, _top_speed){
        this.model = _model;
        this.color = _color;
        this.top_speed = _top_speed;
    }

    get recommended_speed () {
        return this.top_speed * 0.75;
    }

    set recommended_speed (_recommended_speed) {
        this.top_speed = _recommended_speed / 0.75;
    }
}

const tesla = new Car("Model S", "black", 200);
tesla.recommended_speed = 160;

The _recommended_speed parameter is the value we set tesla.recommended_speed to (i.e. 160). So now, the top speed has changed as a result of varying the recommended speed. If we get recommended_speed after the using the setter, its value will be 160

Inheritance

Say that apart from normal cars, we also have smart cars that have extra features and properties. But these cars must include basic properties inherited from a normal car as well (like accelerating, braking, and showing indicators).

So instead of rewriting all the functions and properties in the smart car class, we can inherit them from a normal car

class Car {
    constructor(_model, _color, _top_speed){
        this.model = _model;
        this.color = _color;
        this.top_speed = _top_speed;
    }

    get recommended_speed () {
        return this.top_speed * 0.75;
    }

    set recommended_speed (_recommended_speed) {
        this.top_speed = _recommended_speed / 0.75;
    }
}

class Smartcar extends Car {
    constructor(_model, _color, _top_speed, _voice_assistance_gender){
        super(_model, _color, _top_speed);
        this.voice_assistance_gender = _voice_assistance_gender
    }

    speak (){
        if (this.voice_assistance_gender === "male"){
            console.log("This is a male voice assistant");
        } else{
            console.log("This is a female voice assistant");
        }
    }
}

const smartCar = new Smartcar("smartCar", "blue", 150, "male");
smartCar.speak(); // Logs This is a male voice assistance
console.log(smartCar.recommended_speed); // Logs recommended speed of 112.5

In the above code, the smart car class extends all properties and functions from the car class. It takes in an extra parameter: voice assistant gender.

The super function in the smart car class calls the parent's constructor (the car's constructor) and gives it the input parameters.

Now, if we create a new smart car, we can access the speak function and we can also get and set recommended_speed from the car class.

Static keyword

A function defined with the static keyword does not require an instance of a class to be the value of 'this'. Instead, you can directly pass the class itself as 'this'

Say we want to determine the faster between two cars. We can do this using the static keyword

class Car {
    constructor(_model, _color, _top_speed){
        this.model = _model;
        this.color = _color;
        this.top_speed = _top_speed;
    }

    static faster (car1, car2){
        return car1.top_speed > car2.top_speed ? car1.model : car1.top_speed == car2.top_speed ? "Equal" : car2.model;
    }
}

const tesla = new Car("Model S", "black", 250);
const maybach = new Car("S Class", "white", 125);

const fasterCar = Car.faster(tesla, maybach);
console.log(fasterCar); // Logs Model S

As you can see with the above code, we use the class itself (Car) to call the faster function - not the tesla or maybach instance. This is possible by using the static keyword

Conclusion

Hopefully, you have understood everything you need to know about classes in javascript. These concepts are extremely important in Object Oriented Programming (OOP) and are used in almost every programming language.

That is it from this blog. Thank you for reading and happy coding!

ย