Using functions as keys in JavaScript can be tricky because for js objects, functions are converted to their "toString" form. This poses a problem if two functions have the same body.
var a = function() {};
var b = function() {};
var obj={};
obj[a] = 1;
obj[b] = 2;
In this case, the value of obj[a]
will actually be 2
.
However, using a Map
seems to solve this issue. Here's an example:
var a = function() {};
var b = function() {};
var map = new Map();
map.set(a, 1);
map.set(b, 2);
With the Map
, calling map.get(a)
will return 1
and map.get(b)
will return 2
.
It's important to note whether this behavior is consistent across all browsers or specific to Chrome's implementation of the Map collection. Additionally, understanding how functions are hashed in maps can provide insight into why this works reliably.