Search code examples
javascripthashhashmapprototypejs

Why is a "classic" hash useful?


I've been tasked with maintaining some legacy front-end code that uses a lot of PrototypeJS. I'm getting confused about some things they use in the code. For example, the documentation describes this $H function for creating a "hash" and accessing properties on it in "the classic hash way" which appears to be a simple obj.get('propName').

var h = $H({name: 'John', age: 26, country: 'Australia'});
// Equivalent to:
var h = new Hash({name: 'John', age: 26, country: 'Australia'});
// Can then be accessed the classic Hash way
h.get('country');
// -> 'Australia'

Why is this useful? I'm seeing it used all over the code I'm maintaining and finally decided I need to understand what the original intention was a little better.


Solution

  • From the Prototype.JS docs:

    Because of the nature of JavaScript, every object is in fact a hash; but Hash adds a number of methods that let you enumerate keys and values, iterate over key/value pairs, merge two hashes together, and much more.

    So, basically it's because then you can use keys, values, each, merge, update, etc.