I have the following code. Here I am trying to add click event handler to buttons on a page. The following code does not work and shows output as "[Object MoustEvent]".I know how to fix it (using another closure and wrap onclick handler around it), but I want to understand why I am getting this output. Can someone please explain?
document.addEventListener('DOMContentLoaded', function() {
var prizes = ['A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
for (var btnNum = 0; btnNum < prizes.length; btnNum++) {
// for each of our buttons, when the user clicks it...
document.getElementById('btn-' + btnNum).onclick = function(btnNum) {
var btnNum1 = btnNum;
alert(btnNum1);
};
}
});
<button id="btn-0">Button 1!</button>
<button id="btn-1">Button 2!</button>
<button id="btn-2">Button 3!</button>