On the top of the code I declared table of objects. Then ,in function setup(), I'm trying to, foreach object in a table, add onmouseover function and pass each object as an argument for function pickUp(pick), but then I mouse over this object, console says "pick is undefined". It's weird for me, because I passed pickUps[0] for example and typeof(pickUps[0]) gives me "object". Can someone explain and help with passing each object as an argument?
Code:
var locked = "#4C8299";
var pickedUp = "#CC1B2B";
var released = "#19FFC8";
var pickUps = document.getElementsByClassName("pickUpSquare");
function pickUp(pick){
if (pick.style.background == released){
pick.style.background = pickedUp;
}
}
function setup(){
for (var i = 0; i < pickUps.length; i++){
pickUps[i].onmouseover = function(){
pickUp(pickUps[i]);
}
}
}
window.onload = setup;
The problem is that variable i
in the loop of the setup
function is part of the closure of the inner anonymous function definition.
As such, at the moment when the pickUps[i]
gets used,
the loop has long finished and the value of i
is pickUps.length
,
and so the value of pickUps[i]
is undefined
(it's pointing to a value just beyond the bounds of the array).
One way to fix is to use a function that returns a function,
and pass to it i
or pickUps[i]
as a parameter:
pickUps[i].onmouseover = (function(pick) {
return function() { pickUp(pick); }
})(pickUps[i]);
If you can use ES6, then a simpler solution is to replace var i
with let i
in the for
loop (thanks @alex-kudryashev).