What is Module Pattern in JavaScript: OOP

What is Module Pattern in JavaScript: OOP

·

2 min read

Traditional object-oriented programming like Java, C++, Python etc, make use of the class object to create self-contained and decoupled units of code, which can be treated as block boxes of functionality that can be enhanced, added and removed according to requirements.

A module can be considered as similar to a singleton class in an object-oriented language. In a module, all the variable defined is visible only I the module. Methos in a module has scope and access to the shared private data and private methods with closure in javascript.

IMPLEMENT MODULE PATTERN

In the below example, shop's buying groceries of fruit and vegetable should not be modifiable for any reason. The function shop() returns an object that contains another function that returns a property of the function itself. From the perspective of the scope out of the shop, it can't access any variables inside.

function shop() {
    const fruit = 'mango'; 
    const vegetable = 'brinjal'; 
    return {
        buyFruit: () => fruit; 
        buyVegetable: () => vegetable; 
    }
}
shop().buyFruit(); // mango
shop().buyVegetable(); // brinjal

A closure is easy to cause a memory leak if you overuse it in the wrong way, but you can encapsulate the function safely. To modify the variables, all you need to do is just add the getter and setter function in the return object.

return {
    getFruit: () => fruit; 

    getVegetable: () => vegetable; 

    setFruit: name => fruit = name; 

    setVegetable: name => vegetable = name; 
}

Advantages

  • Reduces clutter with the global namespace
  • supports private data
  • enables unit testability of code

Disadvantage

  • Private methods is not accessible outside the module
  • Private methods are not extensible

Conclusion

The goal of the module is to allow large programs to be assembled using code from disparate sources. Even the initial module developer did not expect to run all the code correctly, after all, changes from the initial stage of code development.

Thank you for reading, I would be posting more content on OOP in JavaScript🤩. No posts on sunday sorry😔

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!