web.onassar.com Archive

I can be reached at onassar@gmail.com.

For my open source work, check out github.com/onassar

Javascript: Using object-references as keys in hashes

View more posts

For some reason, I thought I could use objects as a reference/key in a JS hash. I thought it'd be useful for the key to be a reference to another object/reference since it would allow me to contain a lot of data in a hash while passing it around, but as you can see, the code below runs a little funky:

var a = function(){};
var t = {
    undefined: 's',
    a: 'oliver'

With a response:


The latter two responses are the important ones; referencing t.a will give me the hash-value, whereas using the a object as a key produces an undefined reference.

It seems that using the a character in the t object's definition automatically casts it as a string.


Looking a little more into this, it seems that keys for JS-hashes are always cast as string.

var a = {};
var b = {key: 'value'};
a[b] = 'oliver';
console.log(a['[object Object]']);

The above code will console out the string oliver three times; the internal method for object-properties/attributes seems to cast every getter-request as a string before returning it.