I'm trying to add properties to an object in JavaScript and am having a little trouble making the closure 'remember' the context in which it was created. Here's a code example - there's other properties on the objects, but for this question's purpose, I've omitted them.
dogs = {
fido: {},
milo: {},
ben: {}
};
for (dog in dogs) {
qualities = dogs[dog];
qualities.hungry = function(food) {
return (function(dog) {
return alert(dog + " is hungry for " + food);
})(dog);
};
}
dogs.fido.hungry('biscuits'); // alerts "ben is hungry for biscuits" instead of "fido"