In the following example, concerning closures, I see this:
function addButtons(numButtons) {
for (var i = 0; i < numButtons; i++) {
var button = document.createElement('input');
button.type = 'button';
button.value = 'Button ' + (i + 1);
button.onclick = function(buttonIndex) {
return function() {
alert('Button ' + (buttonIndex + 1) + ' clicked');
};
}(i);
document.body.appendChild(button);
document.body.appendChild(document.createElement('br'));
}
}
window.onload = function() { addButtons(5); };
How come the onclick
method isn't defined as follows?:
button.onclick = (function(buttonIndex) {
return function() {
alert('Button ' + (buttonIndex + 1) + ' clicked');
};
})(i);
Doesn't an IIFE require the following syntax: (function statement)(arguments)
?