Smanjivanje broja globalnih promenljivih i njihovo premeštanje u lokalne (privatne) promenljive donosi više reda u svim jezicima, pa tako i u JavaScript kodu. Ako znamo da se na stranicama često nalazi više različitih skripti ovakvo označavanje ima više smisla.
Module Pattern
//Single Global Variable "Module"
var Module = ( function ( ) {
var privateVariable = "some value";
var privateMethod = function ( ) {
//do something.
}
//returning one anonymous object that will expose public methods.
return {
publicMethod : function ( ) {
//this method can access its private variable and method
//by using the principle of closure.
alert(privateVariable);
privateMethod( );
}
}
})( );
Primer za Module Pattern
//One Global object exposed.
var SearchEngine = (function ( ) {
//Private Method.
var luckyAlgo = function ( ){
//create one random number.
return Math.floor(Math.random()*11);
}
//Returning the object
return {
//Public method.
getYourLuckyNumber : function ( ){
//Has access to its private method because of closure.
return luckyAlgo();
}
}
} ) ( );//Self executing method.
Detaljnije pročitajte ovde