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

Ali Samir
Feb 19
3 min read
post_comment0 Comments
post_like4 Likes

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.

1function createCounter() {
2    let count = 0; // Private variable
3    return {
4        increment: function() {
5            count++;
6        },
7        getCount: function() {
8            return count;
9        }
10    };
11}
12
13let counter = createCounter();
14counter.increment();
15console.log(counter.getCount()); // Output: 1
16console.log(counter.count); // Output: undefined (count is private)
17

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

1class Shape {
2    constructor(color) {
3        this.color = color;
4    }
5
6    // Abstract method
7    calculateArea() {
8        throw new Error('Method must be implemented');
9    }
10}
11
12class Circle extends Shape {
13    constructor(radius, color) {
14        super(color);
15        this.radius = radius;
16    }
17
18    calculateArea() {
19        return Math.PI * this.radius ** 2;
20    }
21}
22
23let myCircle = new Circle(5, 'red');
24console.log(myCircle.calculateArea()); // Output: ~78.54
25

#πŸ“Œ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.

1// Creating a superclass
2class Animal {
3    makeSound() {
4        return 'Some generic sound';
5    }
6}
7
8// Creating a subclass
9class Dog extends Animal {
10    makeSound() {
11        return 'Woof!';
12    }
13}
14
15// Creating instances
16let genericAnimal = new Animal();
17let dog = new Dog();
18
19console.log(genericAnimal.makeSound()); // Output: Some generic sound
20console.log(dog.makeSound()); // Output: Woof!
21


#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!πŸ”₯

You are not logged in.