J
Jang
I noticed something interesting while I was doing some JavaScript.
Lets say I have the code below (simplified greatly from what I have
but it's just about the same).
var objs = {'foo' : {}, 'bar':{}, 'baz':{}};
for (var i in objs) {
objs.o = {};
objs.o.method = function() {
alert(i);
};
}
objs.foo.o.method(); // alerts baz
objs.bar.o.method(); // alerts baz
objs.baz.o.method(); // alerts baz
all three statements above will alert baz, even though the code's
logic should have it alert foo, bar, baz. Can someone explain why that
happens. Also, how would I fix that statement above to work as I
intended to? Thanks.
Lets say I have the code below (simplified greatly from what I have
but it's just about the same).
var objs = {'foo' : {}, 'bar':{}, 'baz':{}};
for (var i in objs) {
objs.o = {};
objs.o.method = function() {
alert(i);
};
}
objs.foo.o.method(); // alerts baz
objs.bar.o.method(); // alerts baz
objs.baz.o.method(); // alerts baz
all three statements above will alert baz, even though the code's
logic should have it alert foo, bar, baz. Can someone explain why that
happens. Also, how would I fix that statement above to work as I
intended to? Thanks.