Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange IE error - between JavaScript global variable and element with name attribute

I tested the following code in IE6, IE7 and IE8 with the same result:

<a name="cd"/>a</a>
<script>
try {
cd = new Date;
} catch(e) {
alert(e);
}
</script>

In all cases an error is thrown. However using

var cd = new Date;

seems to solve the problem.
Does anyone know why that is ?

Here is an example: http://jsbin.com/ahuhu4/2

like image 677
ddallala Avatar asked May 30 '26 02:05

ddallala


2 Answers

When you don't use the var specifier to declare your variable, the variable cd is added as a property to the window object, e.g. window.cd. You already have an object element that is a child of window that is <a name="cd">a</a> which is already typed. You can't specify new Date as a type for this object as it already exists. When you use the var keyword, you are rescoping the variable to a local scope and removing its direct attachment to the window object. This removes the error and allows IE to proceed. Other browser engines handle this differently.

like image 122
Joel Etherton Avatar answered Jun 01 '26 17:06

Joel Etherton


IE does you the great favor of creating properties of window for each page element with an "id" value. It's just a thing. (note: this statement is not really true.)

edit — yes, the element doesn't have "id". OK, well good news - IE also treats references by name as if they were by "id". Recall that document.getElementById("cd") on that page would return a reference to the <a>, just as it would if it had an "id" element.

edit again I think it's not quite correct to say that IE creates actualy window properties, at least by my reading of what the IE8 debugger is telling me. It's more like the interpreter treats an implicit reference to a global variable ("cd" in this case) as a request for it to go look for something in the global page context by that name. To IE, that process includes checking the DOM for elements with that "id" or "name" value. By using the var keyword, you're explicitly telling the interpreter that you're declaring a symbol in the applicable scope (global, here), so that "lookup" process is skipped.

like image 30
Pointy Avatar answered Jun 01 '26 15:06

Pointy