Encapsulating module using the closure

Closure

Large internal function has little function, the function of internal parameters big small function calls.

method one

function myTool(){
    var money = 1000;
    function get() {
        money += 1;
    }
    function send() {
        money -= 1;
    }
    return{
        'get':get,
        'send':send
    }
}

Method Two

(function (w) {
    var money = 1000;
    function get() {
        money += 1;
    }
    function send() {
        money -= 1;
    }
    w.myTool = {
        'get':get,
        'send':send
    }
})(window);

Explanation

  1. Both methods are written in myTool.js

  2. When using the first method, the introduction myTool.js, when the calling code as follows:

    var toolObj = myTool();
    toolObj.get();
    toolObj.send();
    
  3. Use the second method, when in fact equivalent to myTool method is added to the window, the global anywhere, directly or myTool.send myTool.get method can be called internal.

    myTool.get();
    myTool.send();
    
Published 227 original articles · won praise 118 · views 10000 +

Guess you like

Origin blog.csdn.net/KaiSarH/article/details/104376583