Search code examples
javascriptdictionaryprototypeextend

Extending map objects


I don't know how to extend the map object with prototype and hope you can help. I have something like this:

var map = {'one':1, 'two':2};

and I would like to have a method to check for the existence of a key:

if (map.containsKey('one')){...}

How would I extend the map object?


Solution

  • It's dangerous to modify Object.prototype, because it affects all objects and will usually break other libraries you may be using. In general, if you want to add methods to a dictionary-like object, you should create an object for your hash instances to inherit from, like the Prototype Hash object.

    For this specific instance, you should really just use either if (key in map) or if (map.hasOwnProperty(key)).