2012-11-29 3 views
1

같은 개체의 두 번째 개체를 만든 후 개체에 대한 참조를 잃지 않는 문제가있는 사전 개체 또는 맵 개체를 작성했습니다. 시각.
예를 들어, 책과 요약이 포함 된 개체와 자동차 및 비용이 포함 된 개체를 갖고 싶습니다. 두 맵을 두 번째 맵 값으로 설정하면 결과가 종료됩니다.Javascript 개체의 배열/개체 참조 손실 문제를 방지하는 방법

function Dictionary() { 
    var _size = 0; 
    var _dict = new Object(); 
    var _keys = new Array(); 
    var _values = new Array(); 
    var _firstKey = ""; 
    var _lastKey = ""; 

    Dictionary.prototype.put = function() { 
     if (_size == 0) 
      _firstKey = arguments[0]; 

     _keys.push(arguments[0]); 
     _values.push(arguments[1]); 
     _dict[arguments[0]] = arguments[1]; 
     _lastKey = arguments[0]; 
     _size++; 
    }; 

    Dictionary.prototype.firstKey = function() { 
     return _firstKey; 
    }; 

    Dictionary.prototype.lastKey = function() { 
     return _lastKey; 
    }; 

    Dictionary.prototype.get = function() { 
     return _dict[arguments[0]]; 
    }; 

    Dictionary.prototype.size = function() { 
     return _size; 
    }; 

    Dictionary.prototype.entrySet = function() { 
     return _dict; 
    }; 

    Dictionary.prototype.key = function() { 
     return _keys; 
    }; 

    Dictionary.prototype.vaules = function() { 
     return _values; 
    }; 

    Dictionary.prototype.clear = function() { 
     _size = 0; 
     _dict = new Object(); 
     _keys = new Array(); 
     _values = new Array(); 
     _firstKey = ""; 
     _lastKey = ""; 
    }; 

    Dictionary.prototype.remove = function() { 
     var keyIndex; 
     if (_size >= 1) { 
      for (var i = 0; i < _keys.length; i++) { 
       if (arguments[0] == _keys[i]) 
        keyIndex = i; 
      } 

      if (keyIndex === undefined) 
       return undefined 

      _dict = removeItemObject(_dict, arguments[0]); 
      _keys = removeItemArray(_keys, keyIndex); 
      _values = removeItemArray(_values, keyIndex); 

      if (_keys.length > 0 && _keys.length == keyIndex) { 
       _lastKey = _keys[keyIndex - 1]; 
      } 

      if (_keys.length == 0) 
       _lastKey = undefined; 

      if (0 == keyIndex) { 
       if (_keys.length > 1) 
        _firstKey = _keys[1]; 

       else if (_keys.length > 0) 
        _firstKey = _keys[0]; 

       else if (_keys.length == 0) 
        _firstKey = undefined; 
      } 

      _size--; 

     } 
    }; 

    Dictionary.prototype.serialize = function() { 
     var serializedFJSON = "{"; 
     serializedFJSON += "\"size\"" + ":" + _size + ","; 
     serializedFJSON += "\"dict\"" + ":" + JSON.stringify(_dict) + ","; 
     serializedFJSON += "\"keys\"" + ":" + JSON.stringify(_keys) + ","; 
     serializedFJSON += "\"values\"" + ":" + JSON.stringify(_values) + ","; 
     serializedFJSON += "\"firstKey\"" + ":" + "\"" + _firstKey + "\"" + ","; 
     serializedFJSON += "\"lastKey\"" + ":" + "\"" + _lastKey + "\"" + ""; 
     serializedFJSON += "}"; 
     return serializedFJSON; 
    }; 

    Dictionary.prototype.deserialize = function() { 
     var DictionaryClone = JSON.parse(arguments[0]); 
     _size = DictionaryClone.size; 
     _dict = DictionaryClone.dict; 
     _keys = DictionaryClone.keys; 
     _values = DictionaryClone.values; 
     _firstKey = DictionaryClone.firstKey; 
     _lastKey = DictionaryClone.lastKey; 
    }; 

    function removeItemArray(arrayName, key) { 
     var x; 
     var tmpArray = new Array(); 
     for (x in arrayName) { 
      if (x != key) { tmpArray[x] = arrayName[x]; } 
     } 
     return tmpArray; 
    }; 

    function removeItemObject(arrayName, key) { 
     var x; 
     var tmpArray = new Object(); 
     for (x in arrayName) { 
      if (x != key) { tmpArray[x] = arrayName[x]; } 
     } 
     return tmpArray; 
    }; 
} 

var m = new Dictionary(); 
m.put("Lord Of The Rings", "Not One Book But, Three"); 
m.put("Curious George", "I Don't Know Something About a Guy In A Rain Coat"); 

var k = new Dictionary(); 
k.put("Scion FRS", "24955"); 
k.put("Toyota Camry", "22055"); 

k.remove("Toyota Camry"); 

for (items in m.entrySet()) { 
    alert(items + " " + m.entrySet()[items]); 
} 

답변

1

귀하의 방법에 Dictionary.prototype이 (가) 사용 되었기 때문입니다. this로 교체하고 작동합니다 :

this.put = function() 

this.firstKey = function() 

this.lastKey = function() 

... 

, 당신이 당신의 Dictionary [정렬] 클래스에 메서드를 지정하는 this 키워드를 사용. 단순히 함수를 공개하는 것입니다. removeItemArray()과 같은 기능을 보면 사적인 것이며 개체 내에서만 액세스 할 수 있습니다.

프로토 타입이 다르게 작동합니다. dinamically 모든 이미 때문에 자바 스크립트 객체에 구성 개체를 유지 수정할 것이라고의 프로토 타입도 구조에 모든 새로운 인스턴스를 사용 할베이스가

:이 프로토 타입에 대한 this question에 대한 답변에서 좋은 인용입니다 프로토 타입에 대한 포인터

프로토 타입의 목적은 런타임에 개체에 메서드를 추가하는 기능을 제공하는 것입니다. 전통적으로 클래스와 메소드를 미리 정의하는 고전적인 OOP 언어에서 온다면 이것은 다소 외계인 개념으로 보일 수 있습니다.

프로토 타입을 설명하는 다른 질문에 대한 답변을보십시오.

+0

작동하지만 왜 당신이 이것을 사용하기를 꺼리는 시간에 대해 혼란스러워하며 Prototype을 사용해야 할 때 간단한 설명을 해 주시겠습니까? – CubanAzcuy

+0

나는 그 링크를 구체적으로 가지고 있지는 않지만, 응답을 오해하고 그것이 객체로 거슬러 올라가는 인터페이스와 같은 정의되지 않은 상황에서 호출되었을 경우 대비책으로 작동한다고 생각했다. 나는 단지 동적으로 얼마나 동적으로 발생했습니다. 감사!! – CubanAzcuy

관련 문제