1

Consider the following article explaining hashtables / dictionaries in JavaScript:

Can anyone recommend a good Hashtable implementation in Javascript?

Given the accepted answer, I want to be able to do this:

var instance = new Dictionary();
instance['key1'] = 'Foo';
instance['key2'] = 'Bar';
instance['key3'] = 123;
instance['key4'] = true;

but I want the key/value pairs to point to an object within the Dictionary internally. consider the following code structure

var Dictionary = function() {
    var dictionary; // <-- key value pairs should point to this, not to the Dictionary function;

    this.setValue = function(key, value) {
        dictionary[key] = value;
    }

    this.getValue = function() {
        return dictionary[key];
    }
}

Is this possible?

EDIT:

One way I thought of designing the Dictionary object was like so:

var Dictionary = function() {
    this.setValue = function(key, value) {
        this[key] = value;  
    }

    this.getValue = function(key) {
        return this[key];
    }
}

The problems with this are:

  1. I can assign like so instance['key1'] = 'foo'; and read like this instance.key1; I don't want this!!

  2. I can assign this instance['getValue'] = null; and then cannot get a value back because the function is now null!!

Neither of the above should occurr, hence the reason that the set and get functionality should apply to the internal object, not to the dictionary itself.

4

1 回答 1

2
function Dictionary()
{
    this.store = {};    
    this.setValue = function(key, value) {
        store[key] = value;
    }
    this.getValue = function(key)
    {
        return store[key];
    }
    return this;
}
//Testing
var dict = Dictionary();
dict.setValue('key','value');
alert(dict.getValue('key'));//displays "value"
alert(dict.getValue('unassignedKey'));//displays "undefined"
alert(dict['key']);//displays "undefined" (an unfortunate lack of syntactic convenience, we have to go through getValue).
alert(dict.key);//displays "undefined"
var dict2 = Dictionary();
dict2.setValue('key2', 'value2');
alert(dict2.getValue('key'));//displays "undefined"
alert(dict2.getValue('key2'));//displays "value2"
于 2012-08-29T10:27:58.730 回答