Encapsulate your code
Note |
---|
Polluting the global scope can lead to unintentional collisions and overwrites, which in turn lead to unintended behavior. |
You can encapsulate your code in more than one way.
Namespacing
Create a container object for all your functions and variables. For example, the Division of Finance and Administration could use an object named dfa…
Code Block |
---|
let dfa = {}; |
…and add custom functions and variables as members of that object…
Code Block |
---|
dfa.myVar = 'This is my variable';
dfa.myFunction = function() {...}; |
Doing this ensures that any other variable named myVar isn’t affected by DFA’s, and likewise DFA’s isn’t affected by anything defined outside the dfa object.
IIFE
An Immediately Invoked Function Expression (IIFE) is a function that executes at the time of definition. Any variables or functions defined within the IIFE are scoped to that IIFE only and cannot be accessed outside of it.
Code Block |
---|
(function () {
let myVar = 'This is my variable';
let myFunction = function() {...};
})(); |
Info |
---|
It is perfectly fine to use namespacing and IIFEs together, although that is a bit of a belt-and-suspenders scenario. |
Note |
---|
SUPER IMPORTANT - DON’T MESS WITH THE scpa GLOBAL OBJECTscpa is the namespace used by the template itself. If you touch that object in any way with your code. the Earth may very well stop spinning and we’d all be doomed. Hands off. |