Skip to main content

Command Palette

Search for a command to run...

Understanding Object-Oriented Programming in JavaScript

Updated
•4 min read•View as Markdown
Understanding Object-Oriented Programming in JavaScript

In this blog we are going to cover about OOP ( Objected-Oriented Programming ) which is very common and main concept in programming language.

Topic cover:

  • What Object-Oriented Programming (OOP) means

  • What is a class in JavaScript

  • Creating objects using classes

  • Constructor method

  • Methods inside a class

  • Basic idea of encapsulation


What does OOP mean?

OOP ( Object-Oriented Programming ) is a programming paradigm focused on organised code which help to maintain the code and follow DRY principle ( Don't repeat yourself ). In programming it was first introduced in C++ and then follow by other programming languages.

javaScript is multi paradigm language based on prototype but now also support OOP concept which introduced in ES6. OOP based on four pillar which is Abstraction, Encapsulation, Polymorphism and Inheritance.

OOP concept is based on real world life scenario like maintain privacy, shift property parent to child.

What is class in javaScript?

class keyword was introduced in ES6 to make code cleaner and structured way to implement OOP. classes make code reusable enable creation multiple instance of objects.

class Car{
    constructor(name, model){
        this.name = name;
        this.model = model;
    }
    
    newLaunchedCar(){
        return `New car is \({this.name} with latest model \){this.model}`;
    }
}

const rollsRoyce = new Car("Rolls Royce", "phantom");
const mercedes = new Car("Mercedes", "Mercedes-Benz");

console.log(rollsRoyce.newLaunchedCar());
//Output: New car is Rolls Royce with latest model phantom

console.log(mercedes.newLaunchedCar());
//Output: New car is Mercedes with latest model Mercedes-Benz

In this example we created two different instance for different brand ( Rolls Royce and Mercedes ) without writing multiple lines of code, prevent creating separate function for each brand.

We should keep class name first letter capital like "Car". It is a good practice.

Constructor method

A constructor method (function) is used to provide authority to custom initialize of object it runs before any function so values take place. Every class has only their only one constructor.

It runs call automatically when a new instance is created.

class Car{
    constructor(name, model){
        this.name = name;
        this.model = model;
    }
    
    newLaunchedCar(){
        return `New car is \({this.name} with latest model \){this.model}`;
    }
}

const bmw = new Car("BMW", "M5 Sedan (G90)");

We can not provide any another name of constructor. If we don't provide any constructor and by default constructor create empty {}.

Method inside a class

Method are simply functions that define the behaviour of class can call it instance-name . function-name like before example newLaunchedCar is a function.

class Student{
    constructor(name, age){
        this.name = name;    // Property
        this.age = age;      // Property
        this.course = [];    // Property
    }    
    
    addCourse(course){        // Method
        this.course.push(course);
    }

    showStudent(){             // Another method
        return `Name: \({this.name} | Age: \){this.age} | Course: ${this.course.join(", ")}`;
    }
}

const rohan = new Student("Rohan", 23);
rohan.addCourse("React");
rohan.addCourse("Node.js");

console.log(rohan.showStudent());
// Output : Name: Rohan | Age: 23 | Course: React, Node.js

Encapsulation

Encapsulation is use of hiding method and property so they can not be access directly modify data inside the class and prevent to access direct access.

Convection (beginner friendly)

This is the traditional way to create private property or method. This way does not make actual private variable It is just a convection.

class Bank{
    __balance;
    constructor(amount){
        this.__balance = amount;
    }

    showAmount(name){
         return `\({name} bank balance is \){this.__balance}`;
    }
}

const happy = new Bank(300000);
console.log(happy.showAmount("Happy"));
// Output: Happy bank balance is 300000

console.log(happy.__balance);    
// Output: 300000

The __balance variable is accessable outside the class.

Private field

This is the actual way to create private field in modern js instead of __ use #.

class Bank{
    #balance;
    constructor(amount){
        this.#balance = amount;
    }

    showAmount(name){
         return `\({name} bank balance is \){this.#balance}`;
    }
}

const happy = new Bank(1000000);
console.log(happy.showAmount("Happy"));
// Output: Happy bank balance is 1000000

console.log(happy.#balance);    
// Output: Throw error 

Thanks for reading this blog. That's all about OOP.