模块和揭示模块模式
模块模式
Module 模式是一种创建和结构设计模式 ,它提供了一种在生成公共 API 时封装私有成员的方法。这是通过创建一个 IIFE来实现的,它允许我们定义仅在其范围内可用的变量(通过闭包 ),同时返回包含公共 API 的对象。
这为我们提供了一个干净的解决方案,用于隐藏主逻辑,并且只暴露我们希望应用程序的其他部分使用的接口。
var Module = (function(/* pass initialization data if necessary */) {
// Private data is stored within the closure
var privateData = 1;
// Because the function is immediately invoked,
// the return value becomes the public API
var api = {
getPrivateData: function() {
return privateData;
},
getDoublePrivateData: function() {
return api.getPrivateData() * 2;
}
};
return api;
})(/* pass initialization data if necessary */);
揭示模块模式
Revealing Module 模式是 Module 模式中的变体。关键区别在于所有成员(私有和公共)都在闭包中定义,返回值是不包含函数定义的对象文字,并且对成员数据的所有引用都是通过直接引用而不是通过返回的对象完成的。
var Module = (function(/* pass initialization data if necessary */) {
// Private data is stored just like before
var privateData = 1;
// All functions must be declared outside of the returned object
var getPrivateData = function() {
return privateData;
};
var getDoublePrivateData = function() {
// Refer directly to enclosed members rather than through the returned object
return getPrivateData() * 2;
};
// Return an object literal with no function definitions
return {
getPrivateData: getPrivateData,
getDoublePrivateData: getDoublePrivateData
};
})(/* pass initialization data if necessary */);
揭示原型模式
揭示模式的这种变化用于将构造函数与方法分开。这种模式允许我们像对象导向的语言一样使用 javascript 语言:
//Namespace setting
var NavigationNs = NavigationNs || {};
// This is used as a class constructor
NavigationNs.active = function(current, length) {
this.current = current;
this.length = length;
}
// The prototype is used to separate the construct and the methods
NavigationNs.active.prototype = function() {
// It is a example of a public method because is revealed in the return statement
var setCurrent = function() {
//Here the variables current and length are used as private class properties
for (var i = 0; i < this.length; i++) {
$(this.current).addClass('active');
}
}
return { setCurrent: setCurrent };
}();
// Example of parameterless constructor
NavigationNs.pagination = function() {}
NavigationNs.pagination.prototype = function() {
// It is a example of a private method because is not revealed in the return statement
var reload = function(data) {
// do something
},
// It the only public method, because it the only function referenced in the return statement
getPage = function(link) {
var a = $(link);
var options = {url: a.attr('href'), type: 'get'}
$.ajax(options).done(function(data) {
// after the the ajax call is done, it calls private method
reload(data);
});
return false;
}
return {getPage : getPage}
}();
上面的代码应该在一个单独的文件 .js 中,以便在任何需要的页面中引用。它可以像这样使用:
var menuActive = new NavigationNs.active('ul.sidebar-menu li', 5);
menuActive.setCurrent();