Why this code using anonymous function is not working
I 开发者_运维技巧am trying to use anonymous function for adding handler to anchor objects.
I run this code but it doesn't work can you explain why and try to fix it? Thanks:
var obj = document.getElementsByTagName("a");
var items = ["mouseover", "mouseout"];
for (var i = 0; i < items.length; i++) {
(function() {
var item = items[i];
for (var i = 0; i < obj.length; i++) {
obj[i]["on" + item] = function() {
alert("thanks for your " + item);
};
}
})();
}
i
is "hoisted"; in other words, your function is being executed as:
var i;
var item; // vars are hoisted to the beginning
item = items[i];
for (i = 0; i < obj.length; i++) {
obj[i]["on" + item] = function() {
alert("thanks for your " + item);
};
}
So i
in items[i]
is not referring to the outer i
. Instead, i
is undefined
. You should use separate variable names, e.g. j
for the inner loop:
for (j = 0; j < obj.length; j++) {
Second, item
will change so the alert will use the same value each time. To circumvent this, you can use an anonymous function, but the point in them is to pass the value so that it "freezes":
var obj = document.getElementsByTagName("a");
var items = ["mouseover", "mouseout"];
for (var i = 0; i < items.length; i++) {
var item = items[i];
(function(item) {
for (var j = 0; j < obj.length; j++) {
obj[j]["on" + item] = function() {
alert("thanks for your " + item);
};
}
})(item);
}
The reason is that you are using a variable before it has been assigned a value:
var item = items[i];
The variable i
is the local variable that is declared on the next line, not the variable from the surronding scope. Variables have function scope, so eventhough the variable is declared on the next line, it exist in the whole function.
You would need to use a different name for the variable in the function, if you want to be able to access the variable from the surrounding scope. For historic reasons, loop variables are usually named i, j, k as needed.
var obj = document.getElementsByTagName("a");
var items = ["mouseover", "mouseout"];
for (var i = 0; i < items.length; i++) {
(function() {
var item = items[i];
for (var j = 0; j < obj.length; j++) {
obj[j]["on" + item] = function() {
alert("thanks for your " + item);
};
}
})();
}
精彩评论