- It is considered best practice to manage scope using the Module Pattern
- It enables access to both a
public
andprivate
scope in your code - In basic terms you may get this done by wrapping a function inside a function like so:
var Module = (function() {
var _privateMethod1 = function() {
console.log("private 1");
};
var _privateMethod2 = function() {
console.log("private 2");
};
return {
publicMethod1 : function() {
console.log("public 1");
_privateMethod1();
},
publicMethod2 :function() {
console.log("public 2");
}
};
})();
Module.publicMethod1();
Module.publicMethod2();
- In the code above we have created one public module called Module (modules should always use pascal case for easy recognition)
- The module is an IIFE so it calls itself and is available on load
- Inside that function we can define different methods that will be used to get stuff done
- Private methods should always remain local & start with an
_
E.g_privateMethod2
- You never want your private methods to be in the global scope & you can do this by not returning them in the
object
within theModule
- Public methods are also defined within the
Module
and made available to the global scope. - In the code above this is done by returning the public method as a
key : value
pair - To access these public methods in your code you can call them as a method on the
Module
E.g :Module.publicMethod2()
- Within your code the public methods still have access to the private methods and they can be accessed like so :
...
return {
publicMethod1: function() {
privateMethod1();
}
}
- What's going on here is that both private and public methods are local to the
Module
but the public methods are returned in anobject
by passing them askey : value
pairs, thereby making them accessible methods on theModule
which is in the global scope