I want to create a map of functions to its argument. This map will be updated dynamically. Finally all the functions will be called with their corresponding arguments.
Until there's a native cross-browser solution for having objects as keys, you could always implement your own solution. Here's an example of what you could do. In the code below, the ObjectMap
will store a generated key as a property
of the object
that needs to serve as a key
. The property
name that is used to store the key
on the object
is randomized to reduce possible conflicts. The map implementation can then use this property
's value
to retrieve the key
on the object
and then retrieve it's associated value
.
JSPERF: http://jsperf.com/object-map
function ObjectMap() {
this.key = 0;
//you should implement a better unique id algorithm
this.mapId = '_' + Math.floor(Math.random() * 10000);
this.data = {};
}
ObjectMap.prototype = {
set: function (object, value) {
var key = ++this.key;
if (object[this.mapId]) {
return;
}
object[this.mapId] = key;
this.data[key] = value;
},
get: function (object) {
var key = object[this.mapId];
return key? this.data[key] : null;
},
remove: function (object) {
var key = object[this.mapId];
if (!key) {
return;
}
delete this.data[key];
delete object[key];
}
};
function a() {}
var map = new ObjectMap();
map.set(a, 'test');
console.log(map.get(a)); //test