How to pass the Value (not the Reference) of a JS Variable to a Function
In dynamic languages such as JavaScript, variables are passed by reference by default. This means that any changes made to the variable within the function will be reflected in the original variable outside the function. In certain situations, this behavior is undesirable, and you may need to pass the value of a variable to a function instead.
For modern browsers, consider using the let or const keywords to define block-scoped variables:
<code class="js">for (let i = 0; i < results.length; i++) { let marker = results[i]; google.maps.event.addListener(marker, 'click', () => change_selection(i)); }</code>
This approach ensures that each iteration of the loop creates a new scope for the i variable, preventing the issue where every listener uses the value of results.length at the end of the loop.
If you're working with older browsers, create a separate scope for each iteration of the loop by passing the variable as a function parameter:
<code class="js">for (var i = 0; i < results.length; i++) { (function (i) { marker = results[i]; google.maps.event.addListener(marker, 'click', function() { change_selection(i); }); })(i); }</code>
By using an anonymous function and calling it with the variable as the first argument, you effectively pass-by-value and create a closure. This ensures that each listener has its own copy of the i variable, referencing its value at the time the listener was created.
The above is the detailed content of How to Pass the Value (Not the Reference) of a JavaScript Variable to a Function?. For more information, please follow other related articles on the PHP Chinese website!