1

I want to create some functions dynamically with javascript. all function do special work, but with different data(for example, console.log("data")).

config = ['data1', 'data2', 'data3'];
returned = {};
for(var i in config){
    returned[config[i]] = function(){console.log(config[i])};
}

I above code, All functions must log a data, but different data. I want to when I call returned["data1"]() it log data1, But when I call returned["data1"]() it log data3.

Is it possible? How can I do?

Morteza Malvandi
  • 1,656
  • 7
  • 30
  • 73

2 Answers2

2

This is probably what you are looking for.

var returned = {};
['data1', 'data2', 'data3'].forEach(function(element) { 
  returned[element] = function() { console.log(element); };
});
NMunro
  • 890
  • 5
  • 20
2
config = ['data1', 'data2', 'data3'];
returned = {};
config.forEach(function(data){
    returned[data] = function(){
       console.log(data);
    };
});

Edit

You could also extract that inner function so it's slightly more memory efficient:

config = ['data1', 'data2', 'data3'];
returned = {};

function doSpecialWork(data){
    console.log(data);
};

config.forEach(function(data){
    returned[data] = doSpecialWork(data);
});

Edit 2

You could also get silly, but call yourself functional:

config = ['data1', 'data2', 'data3'];

function doSpecialWork(data){
    console.log(data);
};

returned = config.reduce(function(returned, data){
    returned[data] = doSpecialWork(data);

    return returned;
}, {});
rodrigo-silveira
  • 12,607
  • 11
  • 69
  • 123