简体   繁体   中英

How to prevent Javascript Object from Losing Array/Object Reference

I wrote a dictionary object or map object, which ever name you prefer, and I am having an issue not losing the reference to the object after creating a second object of the same time.
For example, I wish to hold a object with books and a summary, and one with cars and their cost. The result ends with both map being set to the second maps values.

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]);
}

It's because you are using Dictionary.prototype on your methods. Replace them with this and it will work:

this.put = function()

this.firstKey = function()

this.lastKey = function()

...

Using the this keyword, you are assigning methods to your Dictionary [sort of] class. You are simply making the functions public. If you look at your functions such as removeItemArray() then these are private and only accessible from within the object.

Prototype works differently. This is a nice quote from an answer to this question about prototype:

The protoype is the base that will be used to construct all new instances and also, will modify dinamically all already constructed objects because in Javascript objects retain a pointer to the prototype

The purpose of prototype is to give the ability to add methods to an object at runtime. This may seem somewhat of an alien concept if you're coming from classical OOP languages, where you traditionally pre-define a class and its methods.

Have a look at the other answers in that question which explain prototype really well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM