我能得到一些关于我的 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();
但这种用法似乎有点草率。我喜欢构造函数。
我像这样重构了一些模块:
更好的方法?
(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');
这种用法对我来说似乎更简洁,而且工作得很好,但我是否正确地使用它?
更进一步
说这个模块用一个包含 Google map 和 jQuery 功能的 div 做一些事情:关于将它变成一个 jQ 插件的任何提示,这样我就可以将它与 var map = $('mapcontainer') 这样的签名一起使用.mapModule();
谢谢!
最佳答案
我已经修改了您的代码段并实际实现了 javascript 揭示模块模式,它提供了使用闭包实现公共(public)和私有(private)功能的机会。
希望这会有所帮助:
/* 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();
关于javascript - 构建 JavaScript 模块的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32828783/