weston wrote:
Matt Kruse wrote:
Ah, yes. In IE, objects with an ID cause that ID to become a global variable
referring to the object. One of the bad "shortcuts" that MS put into IE.
I'm still a bit confused. I do see that properly scoping the variable
as you're talking about fixes the problem. I just can't figure out for
the life of me why it being a global variable would prevent it from
receiving something via the assignment operator. Other global variables
can do that -- right?
Or is there some hidden magic here I"m not aware of...
There is no magic - just an incorrect explanation of the behavior.
Element ID's are not becoming global variables: but elements - with
"id" attribute set to something - are becoming named properties of the
global "window" object. And the "window" object is the default object
of the global execution context. You can consider your script code to
be in the form:
with (window) {
// your code
}
where with(window){} block is being applied seemlessly by the JScript
interpreter. So when meeting a literal on the left side of the
expression without the "var" qualifier, interpreter first looks for an
existing local variable with such name; if failed then it looks for a
global variable with such name; if failed then it looks for window
property with such name. If all above failed then new global variable
will be created.
Samples to play with in the next year:
<html>
<head>
<title>IE's scope 1</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<script type="text/jscript">
var foo = '';
function test(obj) {
foo = obj.innerText;
alert(foo);
}
</script>
</head>
<body>
<div id="foo" onclick="test(t his)" style="cursor:h and">bar</div>
</body>
</html>
<html>
<head>
<title>IE's scope 2</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<script type="text/jscript">
function test(obj) {
alert(foo.inner Text);
// same as:
alert(window.fo o.innerText);
alert(self); // '[object]'
// same as:
alert(window.se lf);
}
</script>
</head>
<body>
<div id="foo" onclick="test(t his)" style="cursor:h and">bar</div>
</body>
</html>
P.S. One of these "noises" VK does.
P.P.S. Happy New Year!