javascript - Understanding a basic modular patterns private and public functions -


i looking @ code of simple demonstration of modular pattern, have :

// global module var mymodule = (function ( jq, _ ) {      function privatemethod1(){         jq(".container").html("test");     }      function privatemethod2(){       console.log( _.min([10, 5, 100, 2, 1000]) );     }      return{         publicmethod: function(){             privatemethod1();         }     };  // pull in jquery , underscore })( jquery, _ );  mymodule.publicmethod(); 

the code pretty straightforward, don't understand what's need publicmethod? why privatemethod1 , privatemethod2 inaccessible? understand privatemethod1 , privatemethod2 classic js functions , publicmethod more of variable assigned hold function.

privatemethod1() , privatemethod2() local functions declared inside module function wrapper. such, visible , callable within function wrapper. can't reached outside module wrapper.

this same local variable inside function.

function somefunc() {     // function declared inside function available     // inside function     function localfunc() {         //     }      // local variable available within     // scope of function     var myvariable = 2; }  // can't call localfunc here - error // because defined in different scope , not available here localfunc(); 

private methods can useful when want create functions or methods public methods can use, not want outside callers able call or use functions/methods.

private variables can used store state public methods or private methods want reference, don't want outside callers have access or able mess with.


Comments

Popular posts from this blog

php - Zend Framework / Skeleton-Application / Composer install issue -

c# - Better 64-bit byte array hash -

python - PyCharm Type error Message -