Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are functions valid keys for javascript object properties?

Tags:

javascript

I'd like to use functions as keys in a javascript object. The following works, at least in Chrome:

var registry = {};
function Foo(){  };
function Bar(){  };
registry[Foo] = 42;
registry[Bar] = 43;
alert(registry[Foo] + " < " + registry[Bar]);

Is this covered by the standard? By which browsers is it supported?

like image 519
Marc-André Lafortune Avatar asked Jun 01 '12 23:06

Marc-André Lafortune


1 Answers

Everything you put between square brackets is converted into a string, and this happens even if you put a function, a date, a regexp... So there, you're actually creating an object like this:

var registry = {
    "function Foo(){  }" : 42,
    "function Bar(){  }" : 43
};

This is a default behaviour, it works in IE too if you were wondering. It was actually exploited by John Resig in his famous addEvent function.

like image 187
MaxArt Avatar answered Oct 23 '22 11:10

MaxArt