Coming back to Modules let us first see one example to see what Modules can do, we will try to simulate the behavior of a Rectangle Class giving in the length of two sides and getting back the area.
Area: 20 Perimeter: 18
Here, the Rectangle() function serves as an outer scope that contains the variables required i.e. length, width, as well as the functions create(), getArea(), and getPerimeter(). All these together are the private details of this
Rectangle module that cannot be accessed/modified from the outside. On the other hand, the publicAPI as the name suggests is an object that consists of three functional members and is returned when the Rectangle function execution is complete. Using the API methods we can create and get the value of area and perimeter of the rectangle.
Note: As we mentioned earlier that modules are the closest concepts of Classes in any other OOP language, many developers might feel like using the ‘new’ keyword while creating a new instance of the Rectangle Module. Rectangle() is just a function, not a proper class to be instantiated, so it’s just called normally. Using new would be inappropriate and actually waste resources.
Executing Rectangle() creates an instance of the Rectangle module and a whole new scope is created and allocated to the function, and therefore a new instance of the member of the functions was generated, as we assigned it to a variable, now the variable had the reference to the allowed publicAPI members. Hence, we can see that running the Rectangle() method creates a new instance entirely separate from any other previous one.
All the member functions have a closure over the length and width, which means that these functions can access them even after the Rectangle() function execution is finished.
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.