我的某些对象的实例有一些名为selected
和方法select()
的值。当触发方法select()
时,我希望将对象的selected
值设置为true
,但此对象的所有其他实例的selected
值为false
- 怎么做?
换句话说 - 如何更改某个对象的所有实例的值?
var Puzzel = function() {
this.selected = false;
};
Puzzel.prototype = {
select: function{
this.selected = true;
//how to set selected = false on every other instance of Puzzel
}
}
答案 0 :(得分:1)
如果您可以依赖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;
}();
答案 1 :(得分:0)
您需要跟踪这些实例。这是一种方法:
(function() {
var instances = [];
window.MyClass = function() {
instances.push(this);
// rest of constructor function
};
window.MyClass.prototype.select = function() {
for( var i=0, l=instances.length; i<l; i++) instances[i].selected = false;
this.selected = true;
};
})();