1

いくつかのオブジェクトの私のインスタンスにはselected、メソッドと呼ばれるいくつかの値がありますselect()。メソッドが起動されたときに、オブジェクトの値を設定しselect()たいのですが、このオブジェクトの他のすべてのインスタンスの値を設定するにはどうすればよいですか?selectedtrueselectedfalse

つまり、オブジェクトのすべてのインスタンスの値を変更する方法は?

    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

ゲッター/セッター(互換性を参照)に依存できる場合は、以下が機能します。

このアプローチには、選択を選択またはチェックするときの一定のオーバーヘッドと、一定のメモリオーバーヘッドがあります。

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

これらのインスタンスを追跡する必要があります。これを行う1つの方法は次のとおりです。

(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 に答える