子產品模式
子產品模式是一種建立型和結構型的設計模式,提供了一種生成公有接口的時候封裝私有成員。可以通過閉包來完成,傳回一個包含公有接口的對象。
這樣我們就可以隐藏主要的邏輯,而隻暴露一個接口:
var Module = (function(/* pass initialization data if necessary */) {
// Private data is stored within the closure
var privateData = ;
// Because the function is immediately invoked,
// the return value becomes the public API
var api = {
getPrivateData: function() {
return privateData;
},
getDoublePrivateData: function() {
return api.getPrivateData() * ;
}
};
return api;
})(/* pass initialization data if necessary */);
暴露式子產品模式
暴露式模式塊式是子產品模式的變種,關鍵的不同點是他們的所有成員(public 和 private的)都在閉包中,傳回值是一個不包含函數定義的對象,并且所有對成員資料的引用都是通過直接引用,而不是通過傳回對象。
var Module = (function(/* pass initialization data if necessary */) {
// Private data is stored just like before
var privateData = ;
// 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() * ;
};
// 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(id, 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 = ; 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', );
menuActive.setCurrent();