JavaScript has many patterns for creating
objects, and there’s usually more than one
way to accomplish the same thing. You can
define your own custom types or your own
generic objects whenever you want.
1.Module Pattern
This pattern is an object-creation pattern designed to create singleton objects with private data. The approach is to use an immediately
invoked function expression (IIFE) that returns an object. An IIFE is a function expression that is defined and then called immediately to produce a
result. That function expression can contain any number of local variables
that aren’t accessible from outside that function. Because the returned
object is defined within that function, the object’s methods have access
to the data. (All objects defined within the IIFE have access to the same
local variables.) Methods that access private data in this way are called
privileged methods.
Example
This pattern allows you to use regular variables as object properties that aren’t exposed publicly. You accomplish this by creating closure functions as object methods. Closures are simply functions that access data outside their own scope. For example, whenever you access a global object in a function, such as window in a web browser, that function is accessing a variable outside its own scope. The difference with the module function is that the variables are declared within the IIFE,and a function that is also declared inside the IIFE accesses those variables.
Top comments (0)