Showing posts with label Immediately Invoked Function Expression. Show all posts
Showing posts with label Immediately Invoked Function Expression. Show all posts

Monday, October 30, 2017

JavaScript: Module Pattern


The module pattern is an object-creation pattern designed to create singleton objects with private data. The basic 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. Methods that access private data in this way are called privileged methods.

Here’s the basic format for the module pattern. In this pattern, an anonymous function is created and executed immediately. (Note the extra parentheses at the end of the function. You can execute anonymous functions immediately using this syntax.) That means the function exists for just a moment, is executed, and then is destroyed.
var yourObject = (function() {

   // private data variables

   return {
      // public methods and properties
   };

}());

The below code creates the person object using the module pattern. The age variable acts like a private property for the object. It can’t be accessed directly from outside the object, but it can be used by the object methods. There are two privileged methods on the object: getAge(), which reads the value of the age variable, and growOlder(), which increments age. Both of these methods can access the variable age directly because it is defined in the outer function in which they are defined.
var person = (function() {

   var age = 25;

   return {
      name: "Nicholas",

      getAge: function() {
         return age;
      },

      growOlder: function() {
         age++;
      }
   };

}());

console.log(person.name);   // "Nicholas"
console.log(person.getAge());   // 25

person.age = 100;
console.log(person.getAge());   // 25

person.growOlder();
console.log(person.getAge());   // 26

Revealing Module Pattern

There is a variation of the module pattern called the revealing module pattern, which arranges all variables and methods at the top of the IIFE and simply assigns them to the returned object. You can write the previous example using the revealing module pattern as follows:
var person = (function() {

   var age = 25;

   function getAge() {
      return age;
   }

   function growOlder() {
      age++;
   }

   return {
      name: "Nicholas",
      getAge: getAge,
      growOlder: growOlder
   };
   
}());
In this pattern, age, getAge(), and growOlder() are all defined as local to the IIFE. The getAge() and growOlder() functions are then assigned to the returned object, effectively "revealing" them outside the IIFE.

Source: The principles of object-oriented JavaScript by Nicholas

Reference: https://coryrylan.com/blog/javascript-module-pattern-basics
Share This:    Facebook Twitter

Total Pageviews

My Social Profiles

View Sonal's profile on LinkedIn

Tags

__proto__ $Browser Access Grants Accessor properties Admin Ajax AllowsCallouts Apex Apex Map Apex Sharing AssignmentRuleHeader AsyncApexJob Asynchronous Auth Provider AWS Callbacks Connected app constructor Cookie CPU Time CSP Trusted Sites CSS Custom settings CustomLabels Data properties Database.Batchable Database.BatchableContext Database.query Describe Result Destructuring Dynamic Apex Dynamic SOQL Einstein Analytics enqueueJob Enterprise Territory Management Enumeration escapeSingleQuotes featured Flows geolocation getGlobalDescribe getOrgDefaults() getPicklistValues getRecordTypeId() getRecordTypeInfosByName() getURLParameters Google Maps Governor Limits hasOwnProperty() Heap Heap Size IIFE Immediately Invoked Function Expression Interview questions isCustom() Javascript Javascript Array jsForce Lightning Lightning Components Lightning Events lightning-record-edit-form lightning:combobox lightning:icon lightning:input lightning:select LockerService Lookup LWC Manual Sharing Map Modal Module Pattern Named Credentials NodeJS OAuth Object.freeze() Object.keys() Object.preventExtensions() Object.seal() Organization Wide Defaults Override PDF Reader Performance performance.now() Permission Sets Picklist Platform events Popup Postman Primitive Types Profiles Promise propertyIsEnumerable() prototype Query Selectivity Queueable Record types Reference Types Regex Regular Expressions Relationships Rest API Rest Operator Revealing Module Pattern Role Hierarchy Salesforce Salesforce Security Schema.DescribeFieldResult Schema.DescribeSObjectResult Schema.PicklistEntry Schema.SObjectField Schema.SObjectType Security Service Components Shadow DOM Sharing Sharing Rules Singleton Slots SOAP API SOAP Web Services SOQL SOQL injection Spread Operator Star Rating stripInaccessible svg svgIcon Synchronous this Token Triggers uiObjectInfoApi Upload Files VSCode Web Services XHR
Scroll To Top