0
我有很多小對象都需要完成非常類似的任務,我想用修飾器來修改這些對象,因爲這樣做對我來說更容易。問題是,一旦訪問這些對象的某些數據時,我也需要觸發內容,同時防止外部訪問實際數據。因此,我正在使用閉包來存儲私人數據併爲外部訪問提供神奇的增效器。最後,我也沒有具體的原因使用構造函數。創建能夠訪問閉包的裝飾器
這是對象和一個非常簡化版本,讓我頭疼的部分:
var Foo = function() {
var hiddenState;
return {
set state (s) {
// Do something that justifies using magical accessors
state = s;
},
get state() {
// Do something that justifies using magical accessors
return state;
}
}
};
var o = new Foo();
o.state = 10;
好了,現在是應該表現與其餘不同,當使用它們的變異符某些對象。所以,我想,我只是覆蓋mutators,就是這樣:
// Let's suppose I have some reason to modify the magical accessors for some objects but not for others
Object.defineProperty(o, 'state', {
get: function() {return hiddenState /*...*/},
set: function (s) {state = s /*...*/}
});
o.state; // Ouch!
這是行不通的。我得到一個參考錯誤,因爲我試圖訪問hiddenState
,因爲它沒有在新的getter/setter對的範圍內定義。
我懷疑JS轉儲只有當我通過新的mutators才能訪問的閉包。有什麼辦法可以解決這個問題嗎?
哇!這正是我期待的!我已經在考慮使用定製功能來保留舊的setter,但這樣好多了。 –