Edit
As @Felix suggested, there is a much better way (in terms of efficiency) to do this -
var myfun = (function () {
var util = {
a: function (){
console.log('method a');
},
b: function (){
console.log('method b');
},
c: function (){
console.log('method c');
},
d: function (){
console.log('method d');
}
};
return function (input1, input2, input3) {
for(var i=0; i<input1.length; i++){
var name = input1[i];
util[name]();
}
};
}());
myfun(['b','d'], 'foo', 'bar');
This way the util
object will be constructed only once, where in the previous way the object will be constructed each time myfun
is called.
However, please note that in this case, the memory footprint will be larger than the previous one as a reference to util
will always be stored in the memory because of closure.
Rather than creating inner functions, try creating an object with methods -
function myfun(input1, input2, input3){
var util = {
a: function (){
console.log('method a');
},
b: function (){
console.log('method b');
},
c: function (){
console.log('method c');
},
d: function (){
console.log('method d');
}
};
for(var i=0; i<input1.length; i++){
var name = input1[i];
util[name]();
}
}
myfun(['b','d'], 'foo', 'bar');