Module pattern- How to split the code for one module into different js files?

前端 未结 4 1532
礼貌的吻别
礼貌的吻别 2020-12-23 12:47

For the module pattern, I\'m doing something like:

(function(namespace) {
    // tons of code
    // blabla
})(window.myGlobalNamespace);

H

4条回答
  •  情歌与酒
    2020-12-23 13:21

    Protected variables in javascript can be achieved by passing in the protected variables as a dependency. The subclass must be created within the parent as only there does it have access to the protected variables. Example jsFiddle

    App = window.App || {};
    App.ParentClass = (function(){
    
       var protectedState = {
          protectedVar: 'wow such protection'
       }
    
       return{
          SubClassInstance: App.SubClass(protectedState), //make the subclass accessible from outside
       }
    })(); //closure gives us privacy
    

    SubClass.js

    App = window.App || {};
    App.SubClass = function(protectedState){
    
        return {
            logProtectedVar : function(){
                //can access protectedState of parent
                console.log(protectedState.protectedVar);
            }
        }
    }// I require protected state to work
    

    main.js

    // protected variable is accessible from parent and subclass and nowhere else
    
    App.ParentClass.SubClassInstance.logProtectedVar();
    // 'wow such protection' 
    

    NOTE: as Charles W. mentioned, this pattern only works when protectedState is an object. If it were a string/int it would be passed by value and changes made in the subclass would not be visible from the parents copy.

提交回复
热议问题