How to use javascript hashes (or hash-table)
Javascript has no hash table object but you can emulate one by creating a simple object and using brackets.
[source:javascript]
var hashPetName = new Object();
hashPetName["dog"] = “Rex”;
hashPetName["cat"] = “Mistigri”;
alert(“My dog’s name is ” + hashPetName["dog"]
+ ” and my cat’s name is ” + hashPetName["cat"] );
[/source]
Great! That’s it about javascript hashes, now I can go groom my cat.
Wait!!!
Why can I use an object to emulate a hash? Can I do the same thing with a Number object? Let’s try with the same code than above but with a Number instead of an Object.
[source:javascript]
var hashPetName = new Number(); // Magic is here!
hashPetName["dog"] = “Rex”;
hashPetName["cat"] = “Mistigri”;
alert(“My dog’s name is ” + hashPetName["dog"]
+ ” and my cat’s name is ” + hashPetName["cat"] );
[/source]
It works!!! What can we understand of this?
All objects are hashes too
When you are javascripting, forget everything you know about other languages, it won’t be any help.
- Javascript is a functional language
- Functions are instances of the Function class
- Classes are a functions
I’m adding to the list
- All objects are hashes
When we create an object, its properties and methods are added to the hash of the object.
[source:javascript]
// Create a class
function TheClass() {
// Adding a property
this.name = “the name”;
}
// Create the object
theObject = new TheClass();
// Alert the property name
alert(theObject.name);
// Alert the property name using the hash
alert(theObject["name"]);
[/source]
In this example, you see that using theObject.theProperty is the same thing that using theObject["theProperty"].
Dynamically add a property/method to the object
In my first example, I didn’t create the property in the constructor before using it. As you saw, it’s easy to dynamically add a property or a method.
[source:javascript]
// Create a class
function TheClass() {
}
var theObject = new TheClass();
theObject["age"] = 3; // Create a new ‘age’ property
theObject.fullName = “Mistigri”; // Create a new ‘fullName’ property
theObject.alertDetail = function() {
alert(this["fullName"] + ” is ” + this.age);
}
theObject["alertDetail"]();
[/source]
Beware! The new property/method will only be available to the instance you’re working on. If you want to add a new property/method to every instances of the class, use prototypes.
Using an array thinking it’s a hash
One of the most common mistake I see is to use an Array object thinking that’s the only one that you can use the brackets to create a hash. Even if it works, it’s not how it should be done. I recommend the use of Object instead.
[Update : A friend of mine pointed me out that I should have talked about hash tables (or associative arrays) instead of hashes.]