2013-03-04 19 views
1

某些對象的實例有一些值,稱爲selected和方法select()。當方法select()被觸發時,我想要將對象的selected的值設置爲true,但selected該對象的所有其他實例的值爲false - 如何操作?JS - 更改對象的所有實例的值

換句話說 - 如何改變一些對象的所有實例的值?

var Puzzel = function() { 
     this.selected = false; 
    }; 

    Puzzel.prototype = {    
     select: function{ 
      this.selected = true; 
      //how to set selected = false on every other instance of Puzzel 
     } 
    } 

回答

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; 
}(); 
+0

很抱歉,我沒有清楚地瞭解你的代碼,你能否發表一點評論,謝謝。 – OPOPO 2013-03-04 21:56:06

+0

@OPOPO,請參閱我的編輯。 – 2013-03-04 21:57:34

+0

@MikeSamuel +1比我的答案要好得多。 – 2013-03-04 22:03:04

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; 
    }; 
})(); 
+0

唯一的辦法是? Isnt可能以某種方式重複.prototype並覆蓋實際值或其他東西? – OPOPO 2013-03-04 21:54:40

+0

這可以防止垃圾收集任何'new MyClass'的結果,在select時需要O(n)開銷,如果構造函數沒有鏈接,則會失敗。 – 2013-03-04 22:02:12

相關問題