构建javascript模块的更好方法是什么?

Kev*_*Ard 6 javascript design-patterns module

我可以在我的js模块上得到一些建议吗?我对js很好,但不是很好的状态:)我是否正在重构我的模块?

我一直在使用这样的js模块模式(粗略的例子,我只是担心结构):

马虎的方式?

/* Module Code */
var MapModule = (function ($) {
    var $_address;
    var $_mapContainer;

    function loadApi() {
        // do something. maybe load an API?
    }

    function someInternalMethod() {
        // do other things
    }

    var pub = {};
    pub.setAddress = function (address) {
        $_address = address;
    };
    pub.getAddress = function () {
        return $_address;
    };
    pub.initialize = function () {
        loadApi();
    }
})(jQuery);

// usage
MapModule.initialize();
Run Code Online (Sandbox Code Playgroud)

但这种用法似乎有些草率.我喜欢施工人员.

我重构了一些像这样的模块:

更好的方法?

(function ($) {
    this.MapModule = function () {
        var $_address;
        var $_mapSelector;
        var $_mapContainer;
        function loadApi() {
            // do something. maybe load an API?
        }
        function someInternalMethod() {
            $_mapContainer = $($_mapSelector);
            // do stuff with the jQ object.
        }

        var pub = {};
        pub.setAddress = function (address) {
            $_address = address;
        };
        pub.getAddress = function () {
            return $_address;
        };
        pub.initialize = function (selector) {
            $_mapSelector = selector;
            loadApi();
        }
    }
})(jQuery);

var map = new MapModule();
map.initialize('#mapcontainer');
Run Code Online (Sandbox Code Playgroud)

这种用法对我来说似乎更清洁,而且效果很好,但我能正确地进行吗?

再迈出一步

假设这个模块使用包含谷歌地图和jQuery功能的div做了一些事情:有关将其转换为jQ插件的任何提示,所以我可以使用它像签名一样 var map = $('mapcontainer').mapModule();

谢谢!

brk*_*brk 1

我修改了您的代码片段,并实际实现了 javascript 显示模块模式,该模式提供了使用闭包实现公共和私有函数的机会。

希望这会有所帮助:

/* Module Code */
var MapModule = (function (module, $, global) {
    var $_address;
    var $_mapContainer;

    // Public functions
    function _loadApi() {
        // Do something, maybe load an API?
    }
    function _someInternalMethod() {
        // Do other things.
    }
    function _initialize = function () {
        _loadApi();
    }

    // Private functions
    function _setAddress = function (address) {
        $_address = address;
    };
    function _getAddress = function () {
        return $_address;
    };

    $.extend(module, {
        loadApi: _loadApi,
        someInternalMethod: _someInternalMethod,
        initialize: _initialize
    });

    return module;
})(MapModule || {},this.jQuery, this);

// Usage
MapModule.initialize();
Run Code Online (Sandbox Code Playgroud)

JSFiddle