如果您可以依赖 getter/setter(请参阅兼容性),那么以下内容将起作用。
这种方法在选择或检查选择时具有恒定的开销,并且具有恒定的内存开销。
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;
}();