J
Justin Constantino
I'm looking for the best way to have a function associate some bit of
data with an object so that it can recall it later, but without adding
any properties to the object - either because the data shouldn't be
seen or accessible by the user, or because the object is a host object
and doesn't necessarily allow properties to be added to it (from what I
understand). Basically, I want to do something like this:
function setData(obj, val) {
obj["someProp"] = val;
}
function getData(obj) {
return obj["someProp"];
}
without having to add -someProp- to -obj-. The only way I've come up
with is this:
var data = [];
function setData(obj, val) {
var n = 0;
while(n < data.length && data[n][0] != obj) n++;
data[n] = [obj, val];
}
function getData(obj) {
var n = 0;
while(n < data.length && data[n][0] != obj) n++;
return data[n] && data[n][1];
}
but since it requires that every item in the array be iterated over,
it's much slower than the original solution when it's used with a lot
of objects. Is there any better/more efficient way to do this?
data with an object so that it can recall it later, but without adding
any properties to the object - either because the data shouldn't be
seen or accessible by the user, or because the object is a host object
and doesn't necessarily allow properties to be added to it (from what I
understand). Basically, I want to do something like this:
function setData(obj, val) {
obj["someProp"] = val;
}
function getData(obj) {
return obj["someProp"];
}
without having to add -someProp- to -obj-. The only way I've come up
with is this:
var data = [];
function setData(obj, val) {
var n = 0;
while(n < data.length && data[n][0] != obj) n++;
data[n] = [obj, val];
}
function getData(obj) {
var n = 0;
while(n < data.length && data[n][0] != obj) n++;
return data[n] && data[n][1];
}
but since it requires that every item in the array be iterated over,
it's much slower than the original solution when it's used with a lot
of objects. Is there any better/more efficient way to do this?