我讀this一篇關於JavaScript的模塊模式和跨聲稱可以保護私有變量/函數跨模塊文件和相互訪問它們的一個片段來了:如何在Javascript模塊模式中使用私有函數/變量?
var MODULE = (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
return my;
}(MODULE || {}));
我有點困惑至於我如何去實現這一點,但我認爲大部分的困惑都來自於不瞭解它是如何工作的;它如何使已經加載的其他腳本能夠利用這些內部值?如何在這個「私人」空間中添加函數和變量?
我的最終目標是提供一種'抽象'函數變量,必須在子模塊中重寫,但仍需要在基本模塊的文件中引用。無可否認,我還沒有玩過這麼多,但主要是因爲我試圖圍繞實際實施如何運作。
我想的是類似以下內容,但它似乎並沒有工作,因爲它不能訪問內部功能:提前
// Preserve state of private variables/functions across modules
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;
};
my._private._unseal();
my._private.bindEvents = function() {
alert("This function should be re-declared in your sub-module.");
};
my._private._seal();
感謝。