Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Revealing module pattern in JavaScript

Tags:

javascript

I stumbled across this post: JavaScript's Revealing Module Pattern. I would like to use this in my project.

Let's imagine I have a function abc and I am calling that function in my main JavaScript file.

Does this pattern make things different? Can anyone show me a basic example of this pattern?

like image 688
theJava Avatar asked Apr 13 '11 09:04

theJava


People also ask

What is the key advantage to the revealing module pattern?

The biggest advantage of revealing module pattern as compared to the module pattern is the code readability aspect. The revealing module pattern is used to provide an abstraction over private implementations by providing public APIs.

What is modular pattern in JavaScript?

The Module Pattern is one of the important patterns in JavaScript. It is a commonly used Design Pattern which is used to wrap a set of variables and functions together in a single scope. It is used to define objects and specify the variables and the functions that can be accessed from outside the scope of the function.

Is a design pattern which let you Organise your JavaScript code in modules and gives better code structure?

Revealing Module Pattern is JavaScript's design pattern that is available for users to actually organize JavaScript's codes in modules which actually gives better code structure and helps in making things either private or public to users.


1 Answers

A small example:

var revealed = function(){    var a = [1,2,3];    function abc(){      return (a[0]*a[1])+a[2];    }     return {       name: 'revealed',       abcfn: abc    } }(); 

in the anonymous function that is initiated to give revealed a value, a and abc are private to that function. What the function returns is an object literal with a name property and a abcfn property, which is a reference to the abc function. The abc function uses the private variable a. This can all be done thanks to the use of closures (everything within the scope of a function can be referenced by everything else in that same function).

Revealed usage:

alert(revealed.name);    //=> 'revealed' alert(revealed.abcfn()); //=> 5 (1*2+3) 
like image 144
KooiInc Avatar answered Oct 13 '22 02:10

KooiInc