Home > Web Front-end > JS Tutorial > ## How to Preserve Variable Values in Event Listeners: Pass by Value or by Reference?

## How to Preserve Variable Values in Event Listeners: Pass by Value or by Reference?

Mary-Kate Olsen
Release: 2024-10-25 03:27:29
Original
622 people have browsed it

## How to Preserve Variable Values in Event Listeners: Pass by Value or by Reference?

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));
}
Copy after login

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);
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template