Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript: Making a variable static when defining a function in a loop?
    primarykey
    data
    text
    <p>Working with Google Maps, I have the following code:</p> <pre><code>var tileNames = ["base", "parking", "access"]; var mapType = {}; for (var i = 0; i &lt; tileNames.length; i++) { var tileOptions = { getTileUrl: function(coord, zoom) { return "/maps/tiles/tiles" + tileNames[i] + "/" + zoom + "_" + coord.x + "_" + coord.y + ".png"; }, tileSize: new google.maps.Size(256, 256) }; mapType[tileNames[i]] = new google.maps.ImageMapType(tileOptions); }; </code></pre> <p>Here is my issue: the "tileNames[i]" in the "getTileUrl" function is undefined when the function is executed. However, the "tileNames" array is only meant to be used here in defining the "mapType" object and thus, unlike the "coord" and "zoom" variables which are passed to the function, I'm looking to use "tileNames[i]" to define that part of the function. Thus, ideally, the function assigned to mapType.parking would look like this...</p> <pre><code>function(coord, zoom) { return "/maps/tiles/tilesparking/" + zoom + "_" + coord.x + "_" + coord.y + ".png"; }; </code></pre> <p>...after the function is defined in the first piece of code. Is there any way to take the value of a variable/array and use it to statically define a function while maintaining the other two variables as variables.</p> <hr> <p><strong>Edit:</strong> Looking at the various answers below, the following is the best I've been able to achieve thus far. While bind might be the ideal approach in a more general scenario, in this specific case, "getTileUrl:" apparently wants a specific syntax and placing the bind around the function defined for it causes errors for Maps. In trying KGZM's suggestion, it works in everything up to date and not in IE8 and below.</p> <pre><code>var tileNames = ["beloit", "parking", "access_p"]; var mapType = {}; for (var i = 0; i &lt;= (tileNames.length - 1); i++) { (function(i) { tileOptions = { getTileUrl: function(coord, zoom) { return "/maps/tiles/tiles" + tileNames[i] + "/" + zoom + "_" + coord.x + "_" + coord.y + ".png"; }, tileSize: new google.maps.Size(256, 256) }; mapType[tileNames[i]] = new google.maps.ImageMapType(tileOptions); })(i); }; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload