Answer the question
In order to leave comments, you need to log in
How to break scopes in nested closures?
In the book "Javascript for PHP developers" by Stoyan Stefanov, in the section "Exercise: onclick Loop", an example is given on the topic of closures - how to manage the scope so that data is passed to nested functions correctly.
I understand how to write it without closures and without nested functions, but I do it by analogy with the previous examples on closures from the book and it doesn’t work.
Task: there are three buttons, when you click on each one, you need to alert its correct index. It is necessary to rewrite the code so that using nested functions correctly "knock down" the connection with scopes and forward the index i in each iteration of for correctly, and not keep a reference to the last value of i.
Link to original: www.jspatterns.com/js4php/closure-dom-loop.html
<!doctype html>
<html>
<body>
<button id="button-1">one</button>
<button id="button-2">two</button>
<button id="button-3">three</button>
<script>
for (var i = 1; i <= 3; i++) {
document.getElementById('button-' + i).onclick = function() {
alert("This is button: " + i);
}
}
</script>
</body>
</html>
Answer the question
In order to leave comments, you need to log in
See what they want from you. In principle, it is enough to replace var with let in a cycle.
or a closure https://jsfiddle.net/DelphinPRO/uyoa9d5f/
Or the same but different https://jsfiddle.net/DelphinPRO/uyoa9d5f/1/
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question