Don’t Repeat Yourself
JavaScript has been developed rapidly in past few years. Developers are able to accumulate experience through reduplicated work. However, in order to improve the work efficiency and code quality, it is suggested to organize and maintain your codebase in a elegant way - Write your own JS Library.
How
|
|
Output Sample:
Why
Use
Strictcan eliminatesilent errorsby changing them to throw errors. Besides,Strict Modecan help JavaScript engines to perform optimizations. Refer to Strict mode for more details.Core Concept - JS Closures & Immediately-Invoked Function Expression
Below is one way of using closures to define public functions that can access private functions and variables which is known as
module pattern:123456(function() {// properties// methods// ...})(window);// Self-Executing Anonymous Functions() is the scope set for this function you are able to create private methods/functions and properties inside local scope.
windowinside () is used as global scope in browser environment.12345678910111213141516171819202122232425// closures examplevar globalVar = 0;(function outerFunc(outerArg) {var outerVar = 3;(function innerFunc(innerArg) {var innerVar = 4;console.log("outerArg = " + outerArg + "\n" +"innerArg = " + innerArg + "\n" +"outerVar = " + outerVar + "\n" +"innerVar = " + innerVar + "\n" +"globalVar = " + globalVar);})(2);})(1);// output:// outerArg = 1// innerArg = 2// outerVar = 3// innerVar = 4// globalVar = 0
