Consider the following code snippet:
for (var i = 0; i < 5; i ) {
var btn = document.createElement('button');
btn.appendChild(document.createTextNode('Button ' i));
btn.addEventListener('click', function(){ console.log(i);});
document.body.appendChild(btn);
}
CodePudding user response:
Well, no matter what button the user clicks, the number 5
will always be logged to the console.
This is because, at the point that the onclick
method is invoked (for any of the buttons), the for loop has already completed and the variable i
already has a value of 5
.
Bonus points, you can read more about execution contexts, variable objects, activation objects, and the internal “scope” property, this contributes to the closure behavior.And you will understand the magic here.