Skip to main content

JavaScript OOP Tutorial | Javascript OOPS tutorial | Complete OOPS tutorial of Javascript

 JavaScript OOP Tutorial

Overview

JavaScript supports Object-Oriented Programming (OOP) principles through its prototype-based architecture. This tutorial will cover key concepts such as classes, objects, data abstraction, data encapsulation, polymorphism, and inheritance, providing step-by-step examples for each.


Four Pillars of Object-Oriented Programming

OOP languages adhere to four primary principles:

  1. Encapsulation: Combining data and methods within objects to ensure data security.
  2. Inheritance: Allowing classes to inherit properties and methods from parent classes, promoting code reuse and enabling method overriding.
  3. Polymorphism: Using the same function in different forms to reduce repetition and enhance code utility.
  4. Abstraction: Hiding complex implementation details to simplify usage.

Is JavaScript Object-Oriented?

To determine if JavaScript is object-oriented, we need to understand the difference between OOP and prototype-based programming.

  • Object-Oriented Programming (OOP): Involves creating classes and instances (objects) from these classes.
  • Prototype-Based Programming: Involves deriving objects from existing objects.

According to MDN Docs, prototypes allow JavaScript objects to inherit features from one another. JavaScript primarily employs prototype-based programming, and the class keyword is syntactic sugar over prototypes, giving it an OOP-like appearance.


Creating Objects in JavaScript

In JavaScript, everything is an object. Arrays, functions, and even primitive values extend the functionality from prototype objects. Here are three ways to create objects:

Using an Object Literal

javascript

const student = { first_name: 'Mary', last_name: 'Green', display_full_name: function() { return `${this.first_name} ${this.last_name}`; } }; console.log(student.display_full_name()); // Output: Mary Green

Using an Object Constructor

javascript

function Student(first_name, last_name) { this.first_name = first_name; this.last_name = last_name; this.display_full_name = function() { return `${first_name} ${last_name}`; }; } const student1 = new Student("Mary", "Green"); const student2 = new Student("Lary", "Smith"); console.log(student2.display_full_name()); // Output: Lary Smith

Using Object.create() Method

javascript

const student = { first_name: 'Mary', last_name: 'Green', display_full_name: function() { return `${this.first_name} ${this.last_name}`; } }; const student1 = Object.create(student); student1.last_name = "Smith"; console.log(student1.display_full_name()); // Output: Mary Smith

No Traditional Classes in JavaScript

JavaScript is prototype-based and does not have traditional classes. The class keyword introduced in ES6 is syntactic sugar for prototype-based inheritance.


Class and Object

Definition:

  • Class: A blueprint for creating objects (instances). It encapsulates data for the object.
  • Object: An instance of a class. It contains properties and methods defined by its class.

Example:

Using ES6 syntax, we can define a class and create objects from it.

javascript

class Student { constructor(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } displayFullName() { return `${this.firstName} ${this.lastName}`; } } // Creating instances of the Student class const student1 = new Student('Mary', 'Green'); const student2 = new Student('Lary', 'Smith'); console.log(student1.displayFullName()); // Output: Mary Green console.log(student2.displayFullName()); // Output: Lary Smith

Data Abstraction

Definition:

  • Data Abstraction: The concept of hiding the complex implementation details and showing only the necessary features of an object.

Example:

Using private fields (introduced in ES2022) to hide internal details.

javascript

class Rectangle { #width; #height; constructor(width, height) { this.#width = width; this.#height = height; } getArea() { return this.#width * this.#height; } } const rectangle = new Rectangle(10, 20); console.log(rectangle.getArea()); // Output: 200 console.log(rectangle.width); // Output: undefined


Another Example of Data Abstraction:

class Bank
{
    #balance; //private variable
    constructor(pincode)
    {
        this.pincode = pincode;
        this.#balance = 10000;
    }
    credit(_amount)
    {
        if(this.login())
        {
            this.#balance += _amount;
        }
        else
        {
            console.log('Invalid pincode');    
        }
    }
    debit(_amount)
    {
        if(this.login())
        {
            if(this.#balance<_amount)
            {
                console.log('Insufficient balance');
                return;
            }
            this.#balance -= _amount;
        }
        else
        {
            console.log('Invalid pincode');    
        }  
    }
    login()
    {
        if(this.pincode===1234)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    get balance()
    {
        if(this.login())
        {
            return this.#balance;
        }
        else
        {
            console.log('Invalid pincode');
        }
    }
}

const obj = new Bank(12345);
obj.credit(5000);
obj.debit(2000);
console.log(obj.balance);

Data Encapsulation

Definition:

  • Data Encapsulation: The bundling of data with methods that operate on that data. It restricts direct access to some of an object's components.

Example:

Encapsulating data using getter and setter methods.

javascript

class Circle { constructor(radius) { this._radius = radius; } get radius() { return this._radius; } set radius(newRadius) { if (newRadius > 0) { this._radius = newRadius; } else { console.error('Radius must be positive'); } } getArea() { return Math.PI * this._radius * this._radius; } } const circle = new Circle(5); console.log(circle.getArea()); // Output: 78.53981633974483 circle.radius = 10; console.log(circle.getArea()); // Output: 314.1592653589793 circle.radius = -5; // Output: Radius must be positive

Polymorphism

Definition:

  • Polymorphism: Poly means many and morphism means form, it provide same name method and operator to be used for multiple functionality. The ability to present the same interface for different data types. In JavaScript, this is often achieved through method overriding and interface implementation.

Example:

Overriding methods in derived classes.

javascript
class Animal {
makeSound() { console.log('Some generic sound'); } } class Dog extends Animal { makeSound() { console.log('Bark'); } } class Cat extends Animal { makeSound() { console.log('Meow'); } } const animals = [new Dog(), new Cat(), new Animal()]; animals.forEach(animal => { animal.makeSound(); // Output: Bark, Meow, Some generic sound });

Inheritance

Definition:

  • Inheritance: A mechanism where a new class inherits properties and methods from an existing class.

Example:

Creating a base class and extending it.

javascript
class Vehicle {
constructor(brand) { this.brand = brand; } start() { console.log(`${this.brand} is starting.`); } } class Car extends Vehicle { constructor(brand, model) { super(brand); this.model = model; } start() { super.start(); console.log(`${this.brand} ${this.model} is ready to go.`); } } const myCar = new Car('Toyota', 'Corolla'); myCar.start(); // Output: // Toyota is starting. // Toyota Corolla is ready to go.

Complete Tutorial Steps

  1. Define a Class:

    • Use the class keyword to define a class.
    • Add a constructor to initialize object properties.
    • Define methods within the class.
  2. Create Objects:

    • Use the new keyword to create instances of the class.
    • Access properties and methods using the dot notation.
  3. Implement Data Abstraction:

    • Hide internal details using private fields.
    • Provide public methods to interact with the hidden data.
  4. Encapsulate Data:

    • Use getter and setter methods to control access to properties.
    • Validate data within setters to enforce rules.
  5. Achieve Polymorphism:

    • Override methods in derived classes to change behavior.
    • Use the same method name in different contexts.
  6. Apply Inheritance:

    • Use the extends keyword to create a subclass.
    • Call the superclass constructor with super.
    • Override methods and add new ones in the subclass.

Comments

Popular posts from this blog

DSA in C# | Data Structure and Algorithm using C#

  DSA in C# |  Data Structure and Algorithm using C#: Lecture 1: Introduction to Data Structures and Algorithms (1 Hour) 1.1 What are Data Structures? Data Structures are ways to store and organize data so it can be used efficiently. Think of data structures as containers that hold data in a specific format. Types of Data Structures: Primitive Data Structures : These are basic structures built into the language. Example: int , float , char , bool in C#. Example : csharp int age = 25;  // 'age' stores an integer value. bool isStudent = true;  // 'isStudent' stores a boolean value. Non-Primitive Data Structures : These are more complex and are built using primitive types. They are divided into: Linear : Arrays, Lists, Queues, Stacks (data is arranged in a sequence). Non-Linear : Trees, Graphs (data is connected in more complex ways). Example : // Array is a simple linear data structure int[] number...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...

Conditional Statement in Python

It is used to solve condition-based problems using if and else block-level statement. it provides a separate block for  if statement, else statement, and elif statement . elif statement is similar to elseif statement of C, C++ and Java languages. Type of Conditional Statement:- 1) Simple if:- We can write a single if statement also in python, it will execute when the condition is true. for example, One real-world problem is here?? we want to display the salary of employees when the salary will be above 10000 otherwise not displayed. Syntax:- if(condition):    statements The solution to the above problem sal = int(input("Enter salary")) if sal>10000:     print("Salary is "+str(sal)) Q)  WAP to increase the salary of employees from 500 if entered salary will be less than 10000 otherwise the same salaries will be displayed. Solution:- x = int(input("enter salary")) if x<10000:     x=x+500 print(x)   Q) WAP to display th...