DEV Community

Cover image for Object Oriented Programming With JavaScript - Part 2 πŸš€
Ali Samir
Ali Samir

Posted on

Object Oriented Programming With JavaScript - Part 2 πŸš€

In the field of software development, Object-Oriented Programming (OOP) is a crucial paradigm that provides a structured way to create complex systems.

In Part 1, we covered the basics of OOP, including Objects and Inheritance.

In Part 2, we will delve deeper into these fundamental concepts, exploring Encapsulation, Abstraction, and Polymorphism.


πŸ”° Encapsulation

Encapsulation encompasses the consolidation of data (properties) and methods (functions) within a singular unit, known as an object. Through this principle, an object gains autonomy over its state while concealing internal workings from external entities.

This encapsulation mechanism relies on closures, scope management, and access control, though it's noteworthy that in JavaScript, conventional access modifiers such as private or public are absent.


Using Closures for Encapsulation πŸ’―

In JavaScript, closures facilitate the establishment of private variables and methods, confining their accessibility within the object's scope and preventing external access.

function createCounter() {
    let count = 0; // Private variable
    return {
        increment: function() {
            count++;
        },
        getCount: function() {
            return count;
        }
    };
}

let counter = createCounter();
counter.increment();
console.log(counter.getCount()); // Output: 1
console.log(counter.count); // Output: undefined (count is private)
Enter fullscreen mode Exit fullscreen mode

Here, count is encapsulated within the createCounter function, and the returned object provides controlled access to its state through increment and getCount methods.



πŸ”° Abstraction

Abstraction simplifies intricate realities by constructing classes or objects tailored to the problem at hand. This process enables developers to concentrate on the core characteristics of an object, shielding irrelevant complexities.

Achieving abstraction entails leveraging tools such as classes, interfaces, and abstract methods. These mechanisms streamline the representation of concepts, fostering clearer and more efficient software design.

Example of Abstraction with Classes

class Shape {
    constructor(color) {
        this.color = color;
    }

    // Abstract method
    calculateArea() {
        throw new Error('Method must be implemented');
    }
}

class Circle extends Shape {
    constructor(radius, color) {
        super(color);
        this.radius = radius;
    }

    calculateArea() {
        return Math.PI * this.radius ** 2;
    }
}

let myCircle = new Circle(5, 'red');
console.log(myCircle.calculateArea()); // Output: ~78.54
Enter fullscreen mode Exit fullscreen mode

πŸ“ŒBenefits of Encapsulation and Abstraction

  • Security: Encapsulation shields sensitive data, revealing only essential functionality to prevent unauthorized access or alteration of internal states.

  • Modularity: Encapsulation fosters the development of independent objects, enhancing modularity and facilitating simpler maintenance procedures.

  • Simplicity: Abstraction streamlines intricate systems by emphasizing core features, and enhancing code clarity and manageability.



πŸ”° Polymorphism

Polymorphism, a fundamental principle within Object-Oriented Programming (OOP), enables objects of various classes to be treated as instances of a shared superclass.

In JavaScript, this capability is realized through method overriding. Subclasses possess the ability to redefine methods inherited from their parent classes, thereby offering distinct implementations while preserving the method's original signature.

// Creating a superclass
class Animal {
    makeSound() {
        return 'Some generic sound';
    }
}

// Creating a subclass
class Dog extends Animal {
    makeSound() {
        return 'Woof!';
    }
}

// Creating instances
let genericAnimal = new Animal();
let dog = new Dog();

console.log(genericAnimal.makeSound()); // Output: Some generic sound
console.log(dog.makeSound()); // Output: Woof!
Enter fullscreen mode Exit fullscreen mode


Conclusion ❀️

JavaScript's incorporation of OOP enables the crafting of adaptable, reusable, and easily maintainable code through the utilization of objects, prototypes, inheritance, encapsulation, abstraction, and polymorphism. Proficiency in these fundamental principles equips developers to architect scalable and streamlined applications within the JavaScript ecosystem, fostering enhanced efficiency and robustness.


Happy Coding!πŸ”₯

Top comments (3)

Collapse
 
ashsajal profile image
Ashfiquzzaman Sajal

Very nice writing.

Collapse
 
shailennaidoo profile image
Shailen Naidoo • Edited

I strongly believe that the pure use of OOP is simply overrated, aside from the examples that you have mentioned above I would like to see a full-blown application using nothing but OOP concepts and it actually works. I know that in Java-land that is all that could have been done for a long time so everything was a class but OOP everything is simply just not feasible and I think a lot of developers know it.

Collapse
 
whosee profile image
Info Comment hidden by post author - thread only accessible via permalink
whosee

Thank you so much for this nice write up. Just a quick question. You wrote:
"JavaScript, conventional access modifiers such as private or public are absent". But isn't privat now added with the #-notation and public the default?

Some comments have been hidden by the post's author - find out more