I was working on a jQuery plugin where I did something like this:
function MyPlugin() { ... }
MyPlugin.prototype = {
foo: function() { ... },
bar: function() { ... },
baz: function() { ... }
}
Now the foo
function ran a loop, which called the bar
function:
foo: function() {
for (i in this.values) {
var result = this.bar(this.values[i]);
}
},
bar: function(value) {
var res = '';
for (i in value) {
// do something
}
return res;
}
Now please ignore what the functions are actually doing here, the focus is the loop itself. I've noticed that, since I'm using i
inside bar
- it changes the value of i
for foo
as well.
I've read about javascript scoping before, but still the example really confuses me. Why is i
slipping between functions like that? How does it make any sense? I ended up just using a different variable, but I'm wondering what's the right way to avoid this sort of problem.
Thanks in advance!