2013-03-04 5 views
1

일부 개체의 인스턴스에는 selectedselect()이라는 값이 있습니다. 방법 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

: 여기에 그 일을하는 한 가지 방법입니다.

이 접근 방식은 선택 사항을 선택하거나 확인하거나 일정한 메모리 오버 헤드를 가질 때 일정한 오버 헤드를 갖습니다.

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

+0

@OPOPO, 내 편집을 참조하십시오. –

+0

@MikeSamuel +1 내 것보다 훨씬 나은 대답. –

0

이러한 인스턴스를 추적해야합니다. 당신이 게터에 의존 할 수 있다면/세터 (compatibility 참조) 한 다음 아래 작동

(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

+0

이것은 'new MyClass'의 결과를 가비지 컬렉션하지 못하게하고, select에 O (n) 오버 헤드가 필요하며 생성자가 연결되지 않으면 실패합니다. –

관련 문제