About function scopes in javascript
- by Shawn
Look at the code below. I want to alert the value of i at the moment that specific listener was added. Is other words, clicking each marker should alert a different value.
Where can I store the value of i in a way that it won't change and be accessible inside the scope of that function?
Here is problematic code:
(it is difficult to test because you need a key from Google)
<html>
    <head>
        <title>a</title>
        <script type="text/javascript">
            function init()
            {
                map = new GMap2(document.getElementById("map_canvas")); // http://code.google.com/intl/es/apis/maps/documentation/reference.html#GMap2
                map.setCenter(new GLatLng(0, 0), 1);    // http://code.google.com/intl/es/apis/maps/documentation/reference.html#GMap2.setCenter
                for(var i = 0; i < 10; i++)
                {
                    var marker = new GMarker(point);    // http://code.google.com/intl/es/apis/maps/documentation/reference.html#GMarker
                    map.addOverlay(marker); // http://code.google.com/intl/es/apis/maps/documentation/reference.html#GMap2.addOverlay
                    GEvent.addListener(marker, "click", function()  // http://code.google.com/intl/es/apis/maps/documentation/reference.html#GEvent.addListener
                    {
                        alert(i);   // Problem: I want the value of i at the moment when the listener is added.
                    });
                }
            }
            window.onload = init;
        </script>
    </head>
    <body id="map_canvas">
    </body>
</html>
Thanks!