I have a function like this:
var eatLunch = (function () {
var sandwiches = [$("#sand1"), $("#sand2")];
return function (eaten) {
for (var i = 0, len = eaten.length; i < len; i++) {
sandwiches[i].attr("class", "eaten-by " + eaten[i].by)
}
};
}());
eatLunch([
{
result: "good",
by: "Adam"
},
{
result: "meh",
by: "Adam"
}
]);
The goal is to cache the dom # sand1 and # sand2 elements in close to reduce the amount of interference this function should perform. Without closing, elements should be assigned to variables every time I call a function.
However, the attr method does not work. Upon further inspection, sandwiches [i] are determined and it has the attr method. The function does not throw an error, it just continues the loop, but the dom elements are not updated.
If I move the sandwiches to a local volume, it works fine, but it's more expensive. See below:
var eatLunch = function (eaten) {
var sandwiches = [$("sand1"), $("sand2")];
for (var i = 0, len = eaten.length; i < len; i++) {
sandwiches[i].attr("class", "eaten-by " + eaten[i].by)
}
};
eatLunch([
{
result: "good",
by: "Adam"
},
{
result: "meh",
by: "Adam"
}
]);
What's going on here?
Adam source
share