469,360 Members | 1,807 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,360 developers. It's quick & easy.

Associating data with an object without adding properties to it

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?

Aug 10 '05 #1
2 1057
Using closures may give you a partial answer, at least for your own
objects.

It may be of no assistance for host objects, and it also involves
creating two methods.

function myObject()
{
var p={};

this.setPrivate=function(a,b)
{
p[a]=b;
}

this.getPrivate=function(a,b)
{
return p[a];
}
}

function fTest()
{
var oObj1=new myObject();
var oObj2=new myObject();

oObj1.setPrivate("Test",2);
oObj2.setPrivate("Test",3);

alert(oObj1.getPrivate("Test"));
alert(oObj2.getPrivate("Test"));
}

Aug 10 '05 #2
Also, it may help if you could explain with an example the context.
I.e. for what purposes would you wish to associate specific data with a
specific object other than as a property.

Aug 10 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

10 posts views Thread by Richard A. DeVenezia | last post: by
16 posts views Thread by D Witherspoon | last post: by
9 posts views Thread by Jimmy Cerra | last post: by
19 posts views Thread by Simon Verona | last post: by
4 posts views Thread by Dries De Rudder | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
1 post views Thread by Marylou17 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.