模組和揭示模組模式
模組模式
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();