For the module pattern, I\'m doing something like:
(function(namespace) {
// tons of code
// blabla
})(window.myGlobalNamespace);
H
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.