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

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,740
Latest member
JudsonFrie

Latest Threads

Top