如果你能依靠getter/setter方法(見compatibility),那麼下面會工作。
這種方法在選擇或檢查選擇時具有不變的開銷,並且存儲常數不變。
var Selectable = function() {
// Define your constructor normally.
function Selectable() {
}
// Use a hidden variable to keep track of the selected item.
// (This will prevent the selected item from being garbage collected as long
// as the ctor is not collectible.)
var selected = null;
// Define a getter/setter property that is true only for the
// item that is selected
Object.defineProperty(Selectable.prototype, 'selected', {
'get': function() { return this == selected; },
// The setter makes sure the current value is selected when assigned
// a truthy value, and makes sure the current value is not selected
// when assigned a falsey value, but does minimal work otherwise.
'set': function (newVal) {
selected = newVal ? this : this == selected ? null : selected;
}
});
// Define a select function that changes the current value to be selected.
Selectable.prototype.select = function() { this.selected = true; };
// Export the constructor.
return Selectable;
}();
很抱歉,我沒有清楚地瞭解你的代碼,你能否發表一點評論,謝謝。 – OPOPO 2013-03-04 21:56:06
@OPOPO,請參閱我的編輯。 – 2013-03-04 21:57:34
@MikeSamuel +1比我的答案要好得多。 – 2013-03-04 22:03:04