1

我的某个对象的实例有一些称为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
        }
    }
4

2 回答 2

1

如果您可以依赖 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;
}();
于 2013-03-04T21:54:35.993 回答
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;
    };
})();
于 2013-03-04T21:53:04.870 回答