简体   繁体   中英

How to pass the value of a variable instead of a reference into a function in Javascript

If I use the code below, the alert will say 10 . I want it to say 5 .

var a = 5;
var b = document.getElementById("element").onclick = ()=>alert(a);
a = 10;

How can I create an event listener that uses the value of a variable from the time it was created, rather than a reference that will change if I modify value later?

Use an IIFE that captures the current value of a .

 var a = 5; document.getElementById("element").onclick = ((x) => ()=>alert(x))(a); a = 10;
 <button id="element">Click</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM