Sample application of self executing anonymous functions in avascript

  • 2020-03-30 03:58:42
  • OfStack

Self-executing anonymous functions in Javascript
Format:


(function(){ 
// code  
})(); 

Explanation: this is rather elegant code (if you see it for the first time, you might get confused:)), where the first pair of parentheses surrounding the function(function(){}) returns an unnamed function to the script, followed by an empty pair of parentheses that immediately execute the returned unnamed function, with the parameters of the anonymous function inside.
Here's an example with a parameter:


(function(arg){ 
alert(arg+100); 
})(20); 
//  This example returns 120 .  

Important use: you can use it to create a namespace, so as long as you write all your code in this special function wrapper, the outside world won't be able to access it unless you allow it


(function(){ 
function $(id){ 
return document.getElementById(id); 
} 
function __addClass(id,className,classValue){ 
$(id).style.className=classValue; 
} 
window['mySpace']={}; 
window['mySpace']['addClass']=__addClass; 
})();

The above example USES this pseudo-namespace to encapsulate and protect all of its functions, objects, and variables. Also, because they are in the same function, they can refer to each other. To globalize the protected code, a subsequent pair of parentheses tells the browser to execute the returned anonymous function immediately, and during the execution a method assigns s value to the window, so that only addClass can be executed externally and s/s is protected. I can call it myspace.addclass ('oneId','font-width','bold')


Related articles: