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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
(function(window){ /* function scope starts here */
'use strict';
function define_library(){
var LogDecorator = {}; // will be returned as a global variable
var logging = true; // disable/enable logging globally
var logPrefix = "----------------Start---------------------";
var logSuffix = "-----------------End---------------------";
LogDecorator.log = function(option, targetObj){
if(logging === true){
console.log(logPrefix);
console.log(`Option: ${option}`);
console.log('Target Object:');
console.log(targetObj);
console.log(logSuffix);
}
}
return LogDecorator;
}
//define globally if it doesn't already exist
if(typeof(LogDecorator) === 'undefined'){
window.LogDecorator = define_library();
}
else{
console.log("LogDecorator has already been defined.");
}
})(window); /* function scope ends */

Output Sample:

Test SampleTest Sample

Why

  1. Use Strict can eliminate silent errors by changing them to throw errors. Besides, Strict Mode can help JavaScript engines to perform optimizations. Refer to Strict mode for more details.

  2. 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:

    1
    2
    3
    4
    5
    6
    (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. window inside () is used as global scope in browser environment.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    // closures example
    var 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