1

I want to define several methods from an array of method names like so:

var methodNames = ['foo', 'bar', 'baz'],
    randomObject = {}, method;

for( var i = methodNames.length - 1; i >= 0; --i ){
  method = methodNames[ i ];

  randomObject[ method ] = function(){
    console.log( method );
  }
}

So that I end up with an object randomObject, which has all the methods defined doing the exact same thing. The problem is, every method logs 'foo' instead of the name of the method being called. How can I make the variable method persist when the method is called?

Dirk Smaverson
  • 863
  • 7
  • 8

2 Answers2

4

I can't tell if this is the best way to use a closure, but I think this is working...

UPDATE:

http://jsfiddle.net/ZDrCK/1/

var methodNames = ['foo', 'bar', 'baz'],
    randomObject = {},
    method;

for (var i = methodNames.length - 1; i >= 0; --i) {
    method = methodNames[i];

    randomObject[method] = (function(met){
        return function () {
            console.log(met);
        }
    })(method);
}

randomObject.baz();
randomObject.bar();
randomObject.foo();
Ian
  • 50,146
  • 13
  • 101
  • 111
  • Crap, re-read and see that each function shouldn't be called immediately... – Ian Oct 27 '12 at 00:15
  • It's not about using a **closure**, it's about creating a new scope by executing a function. OP is already using a closure. – Felix Kling Oct 27 '12 at 00:51
  • @FelixKling True, but isn't executing a function considered a closure? I know it's just terminology, but still – Ian Oct 27 '12 at 21:49
  • Not really. A closure is a function that has access to variables defined in a higher/outside scope (that's actually all of it). http://en.wikipedia.org/wiki/Closure_(computer_science) – Felix Kling Oct 28 '12 at 01:58
1

You should wrap it in a self-executing closure:

for (var i = methodNames.length - 1; i >= 0; --i) {
    (function(method) {
        randomObject[method] = function() {
            console.log(method);
        };
    })(methodNames[i]);
}​
David G
  • 94,763
  • 41
  • 167
  • 253