Home >Web Front-end >JS Tutorial >How Can Closures Help Avoid Shared References When Creating Event Handlers in JavaScript Loops?
Creating Event Handlers with Closure in Javascript
In Javascript programming, it is common to create event handlers inside loops. However, when using syntax like select.onchange = function(), it is crucial to be aware of the potential issue with shared references.
When an event handler is assigned within a loop using this syntax, it can lead to all event handlers pointing to the same variables, which will contain the final values assigned within the loop. This can result in the same parameters being passed to the event handler for all events, regardless of the individual iteration.
To resolve this issue and prevent shared variable references, a closure is necessary. A closure involves creating an inner function that captures the variables from the outer function by reference. This inner function can then be used as an event handler, ensuring that each event handler has its own copy of the variables from the corresponding loop iteration.
For the given example in the question, the code below demonstrates how to implement a closure and pass the correct parameters to the event handler:
<code class="javascript">var blah = xmlres.getElementsByTagName('blah'); for(var i = 0; i < blah.length; i++) { var td = document.createElement('td'); var select = document.createElement('select'); select.setAttribute("...", "..."); select.onchange = function(s,c,a) { return function() { onStatusChanged(s,c,a); } }(select, callid, anotherid); td.appendChild(select); }</code>
In this code, the inner, anonymous function returns the function that is used as the event handler. The (s,c,a) parameters within the function are captured by reference, ensuring that each event handler has its own unique set of variables. As a result, the correct parameters will be passed to the onStatusChanged method when an event occurs.
The above is the detailed content of How Can Closures Help Avoid Shared References When Creating Event Handlers in JavaScript Loops?. For more information, please follow other related articles on the PHP Chinese website!