Preserving Variable Values in Event Listeners: Passing by Value vs. by Reference
When assigning variables inside a loop and adding event listeners, it's important to consider whether you want to pass the variable's value or reference to the listener.
In your case, you encountered an issue where each listener was using the final value of i instead of the intended value at the time of listener creation. This problem arises because JavaScript uses variable hoisting with the var keyword, where variables are declared at the top of their scope, giving them a global scope (even if declared within a block).
To address this, you can employ two techniques:
Using Block-Scoping with let or const:
In modern browsers, you can utilize the let or const keywords to create block-scoped variables. This ensures that variables are declared within their containing block and cannot be accessed outside of it.
for (let i = 0; i < results.length; i++) { let marker = results[i]; google.maps.event.addListener(marker, 'click', () => change_selection(i)); }
Creating Closures with Anonymous Functions:
In older browsers that do not support block-scoped variables, you can create a closure to preserve the current value of i for each iteration. This involves wrapping the event listener creation inside an anonymous function and passing i as a parameter:
for (var i = 0; i < results.length; i++) { (function (i) { marker = results[i]; google.maps.event.addListener(marker, 'click', function() { change_selection(i); }); })(i); }
By passing i into the anonymous function as the first argument, you're effectively passing the value of i at the time of the function call to the listener.
The above is the detailed content of ## How to Preserve Variable Values in Event Listeners: Pass by Value or by Reference?. For more information, please follow other related articles on the PHP Chinese website!