JavaScript coding patterns

Another post on JavaScript coding. This time I like to introduce the coding patterns that helps you to make variables and functions on your code less vulnerable to overwriting by other's variables and functions on the same page.



  1. SINGLETON
  2. MODULE PATTERN
  3. REVEALING MODULE PATTERN
Among these, I found the "Revealing Module Pattern" as a good pattern to follow. See a sample code below:

< script language="javascript">
var myCar = function(){
 var startEngine = function(){
  alert('Engine Started');
 }

 var turnKey = function(){
  alert('Key turned');
  startEngine();
 }

 return{
  turnKey:turnKey
 }
}();// the parenthesis just after closing braces cause the function to execute and return.

myCar.turnKey();
myCar.startEngine();


Here, I have declared "myCar" as an anonymous function. All the functions and variables inside this function are now private. That is, they cannot be called from outside this function. Now, we will create the references of the functions that should be made public and return them. Here, we only made the "turnKey" function public.
Note the pair of parenthesis next to the closing of the anonymous function "myCar". This parenthesis cause the function to immediately execute and return. So, when the code is run, we will have the "myCar" function available in the page.
So, I can call the myCar.turnKey() function. If I try to call the myCar.startEngine() function, this will create and error as the function is private to "myCar".

Comments

Popular posts from this blog

Hide notification content in Android lock screen for Messages, email, whatsapp and selected apps.