Home > Web Front-end > JS Tutorial > How to Pass the Value (Not the Reference) of a JavaScript Variable to a Function?

How to Pass the Value (Not the Reference) of a JavaScript Variable to a Function?

Patricia Arquette
Release: 2024-10-25 08:00:03
Original
717 people have browsed it

How to Pass the Value (Not the Reference) of a JavaScript Variable to a Function?

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>
Copy after login

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>
Copy after login

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!

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