Reputation: 73
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?
Upvotes: 2
Views: 114
Reputation: 780949
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>
Upvotes: 5