If the "with" statement in Javascript creates a new scope, why does the following code not work as e

Posted by Jian Lin on Stack Overflow See other posts from Stack Overflow or by Jian Lin
Published on 2010-04-30T07:00:32Z Indexed on 2010/04/30 7:07 UTC
Read the original article Hit count: 172

Filed under:
|
|
|

If the "with" statement in Javascript creates a new scope, shouldn't clicking on the links show a different x which are in different scopes? It doesn't.

<a href="#" id="link1">ha link 1</a>
<a href="#" id="link2">ha link 2</a>
<a href="#" id="link3">ha link 3</a>
<a href="#" id="link4">ha link 4</a>
<a href="#" id="link5">ha link 5</a>


<script type="text/javascript">

    for (i = 1; i <= 5; i++) {

        with({foo:"bar"}) {
            var x = i;
            document.getElementById('link' + i).onclick = function() { alert(x); return false; }
        }

    }

</script>

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about scope