Wednesday 9 November 2016

Javascript module

Module is the common usage of closure.

 function User(){  
      var username, password;  
      function doLogin(user,pw) {  
           username = user;  
           password = pw;  
           // do the rest of the login work  
      }  
      var publicAPI = {  
           login: doLogin  
      };  
      return publicAPI;  
 }  

Usage

 var fred = User();  
 fred.login('fred', '123');  

Attempt to access the invisible method doLogin() will generate an error

 fred.doLogin('fred', '123');  

TypeError: fred.doLogin is not a function