ゲッター/セッター(互換性を参照)に依存できる場合は、以下が機能します。
このアプローチには、選択を選択またはチェックするときの一定のオーバーヘッドと、一定のメモリオーバーヘッドがあります。
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;
}();