Here是關於JavaScript中各種「模塊模式」的很好的文章。關於如何擴充模塊或名稱空間以及維護跨文件私有狀態,有一個很好的小節。也就是說,單獨文件中的代碼將按順序執行,並在執行後正確地增加名稱空間。
我還沒有徹底探索過這種技術,所以沒有承諾......但這裏是基本的想法。
dashboard.js
(function(window){
var dashboard = (function() {
var my = {},
privateVariable = 1;
function privateMethod() {
// ...
}
my.moduleProperty = 1;
my.moduleMethod = function() {
// ...
};
return my;
}());
window.Dashboard = dashboard;
})(window);
dashboard.ajax.js
var dashboard = (function (my) {
var _private = my._private = my._private || {},
_seal = my._seal = my._seal || function() {
delete my._private;
delete my._seal;
delete my._unseal;
},
_unseal = my._unseal = my._unseal || function() {
my._private = _private;
my._seal = _seal;
my._unseal = _unseal;
};
// permanent access to _private, _seal, and _unseal
my.ajax = function(){
// ...
}
return my;
}(dashboard || {}));
dashboard.retrieveContent。JS
var dashboard = (function (my) {
var _private = my._private = my._private || {},
_seal = my._seal = my._seal || function() {
delete my._private;
delete my._seal;
delete my._unseal;
},
_unseal = my._unseal = my._unseal || function() {
my._private = _private;
my._seal = _seal;
my._unseal = _unseal;
};
// permanent access to _private, _seal, and _unseal
my.retrieveContent = function(){
// ...
}
return my;
}(dashboard || {}));
名稱命名空間一些不同的東西? – 2010-08-05 00:50:42
我想這是一種選擇,但是我希望將所有東西都包含在一個命名空間下,因爲我認爲它會更有序。 – 2010-08-05 01:14:52