I have a problem getting the value of ‘name’ displayed with the following:
for (var name in array) {
var hoverIn = function() {
alert(name);
};
var hoverOut = function() {
};
thing.hover(hoverIn, hoverOut);
}
What I get is an alert window with the last value of name. Clearly I am doing something wrong and I suspect it’s a simple fix. Can anyone help?
Thanks.
It’s closure problem,
name, after that iteration is the lastnameinarray, and callback for hovers isn’t executed right away when the iteration happens, thus when the hover function is actually executed,namewill always be the last inarray.You need to use IEFE (Immediately executed function expression):
To avoid duplicates of
(function() { })()(which honestly is getting tiring to look at), you could also, as @pimvdb pointed out, wrap the whole body in a closure: