0

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"
iseetheseals
  • 35
  • 1
  • 5

1 Answers1

0

You've got your IEFE messed up. It needs to be around the assigned function, otherwise it won't be able to establish the context for the closure. When you call the IEFE inside the method only, dog (the argument) will already have the false value.

Use

for (dog in dogs) {
  dogs[dog].hungry = (function(dog) {
    return function(food) {
      return alert(dog + " is hungry for " + food);
    };
  })(dog);
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375