objects as indexes of objects

J

Jeff Thies

I have this:

<div id="a">
a
</div>

<div id="b">
b
</div>


<script type="text/javascript">
var X = new Object();

var a = document.getElementById('a');
var b = document.getElementById('b');

X[a] = 'A';

if(X[a]){alert('object a')} // I get the expected alert

if(X){alert('object b')} // There is no X defined but I still get
an alert. Why?


</script>

I'm initializing an instance for various objects on a page and I want to
keep track of them. How do I do that?

Jeff
 
T

Thomas 'PointedEars' Lahn

Jeff said:
I have this:

<div id="a">
a
</div>

<div id="b">
b
</div>


<script type="text/javascript">
var X = new Object();

You should not be using identifiers starting with a capital letter for non-
constructors or non-constants.
var a = document.getElementById('a');
var b = document.getElementById('b');

X[a] = 'A';

document.getElementById() returns a reference to a host object, the `null'
value or an undefined value. You cannot reasonably use that as property
name. Depending on your DOM implementation, this could be the equivalent of

X["[object HTMLDivElement]"] = 'a';

whereas "[object HTMLDivElement]" would be the string representation of that
host object.

Perhaps you meant

X.A = a;

which is equivalent to

X["A"] = a;

(But again, refrain from using leading capital characters for property names
unless the property refers to a constructor or is used like a constant.)
if(X[a]){alert('object a')} // I get the expected alert

if(X){alert('object b')} // There is no X defined but I still get
an alert. Why?


A) You have misunderstood what X is.
B) Your ECMAScript implementation is borken.
C) You have not posted the real code.
</script>

I'm initializing an instance for various objects on a page and I want to
keep track of them. How do I do that?

Please restate your request.


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top