Content deleted Content added
Corrected the english. |
m Fix grammar and styling of JS example. |
||
Line 212:
===Example 2: Accidental reference to a bound variable===
For this example the expected behaviour would be that each link should emit its id when clicked; but because the variable 'e' is bound to the scope above, and lazy evaluated on click, what actually happens is that each on click event emits the id of the last element in 'elements' bound at the end of the for loop.<ref>{{cite web |title=Closures |url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures#Creating_closures_in_loops_A_common_mistake |website=MDN Web Docs |access-date=20 November 2018}}</ref>
<syntaxhighlight lang="javascript">
var elements = document.getElementsByTagName('a');
// Incorrect: e is bound to the function containing the 'for' loop, not the closure of "handle"
for (var e of elements) {
e.onclick = function handle() { alert(e.id); } }
</syntaxhighlight>
Again here variable <code>e</code> would need to be bound by the scope of the block using <code>handle.bind(this)</code> or the <code>let</code> keyword.
|