DEV Community

Shubham_Baghel
Shubham_Baghel

Posted on

Object Patterns in Javascript

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

var myobject =(function(){ //private data variables return{ //public methods and properties } }());

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.

var object= (function() { var age = 20; return { name: "myname", getAge: function() { return age; }, getOlder: function() { age++; } }; }()); console.log(object.name); // "myname" console.log(object.getAge()); // 25 object.age = 100; console.log(object.getAge()); // 25 object.getOlder(); console.log(object.getAge());

Top comments (0)