how to use the javascript module pattern in a real example?

后端 未结 5 1925
陌清茗
陌清茗 2021-01-31 05:59

I am trying to understand the JavaScript Module Pattern. I\'ve seen examples of what it should look like, but I don\'t understand how to use it.

For example, a few thing

5条回答
  •  鱼传尺愫
    2021-01-31 06:51

    The revealing module pattern is used like this:

    var moduleName = (function () {
        var privateVariable = 'private';
    
        var privateMethod = function () {
            alert('this is private');
        };
    
        // this is the "revealed" part of the module
        return { 
            publicVariable: 'public',
            publicMethod: function () {
                alert('this is public');
            }
        };
    }());
    

    You can also define the public variables/methods as privates and then expose a reference to them, making them public. This is a matter of preference.

    In your example, if you wanted addMessage to be part of the module, you would do it like this:

    var moduleName = (function () {
        // this becomes public due to the reference exposure in the return below
        var addMessage = function () {
            // do whatever
        };
    
        // this is the "revealed" part of the module
        return { 
            addMessage: addMessage
        };
    }());
    
    moduleName.addMessage();
    

提交回复
热议问题