Strange IE bug - between global JavaScript 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 occurs. However using

var cd = new date;

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

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

+3
source share
3 answers

var , cd , . window.cd. , <a name="cd">a</a>, . , . var, . IE . -.

+6

IE window "id" . . (: .)

edit — , "id" . , - IE , "id" . , document.getElementById("cd") <a> , "id" .

edit again , , IE window , , , IE8. , ( "cd" ) , - . IE DOM "id" "name". var, , (, ), "lookup" .

+3

// Firefox . IE, # 9, Opera 10, Safari 5 Chrome 6, rollcall id'd .

, ...

function a1(id){
    try{
        window[id].style.color= 'red';
    }
    catch(er){
        return er.message+'\n'+'window.'+id+' = '+window[id];
    }
    return 'window.'+id+'='+window[id];
}
function a2(id){
    window[id]= 'red';
    return 'window.'+id+'='+window[id]
}

/*

firefox [idstring] - undefined.

, IE document.all.

  • :

(a1 ( 'idstring'))

colors the element red and returns[object HTMLButtonElement] 
(returns [object Object] in older ie browsers)
  • : alert (a2 ('idstring')) 'red'

  • alert (a1 ('idstring'))

  • - 'window [id].style'

  • "" undefined
  • The result of the expression 'window [id] .style' [undefined] is not an ot object
  • Expected Object

* /

0
source

Source: https://habr.com/ru/post/1769364/


All Articles