I'm currently writing an API that allows users to load modules (to give a kind of plugin functionality) via a loadModules() function:
Code in full:
var LC = (function(){
var alertModule = {
alertName: function(name) {
alert(name);
},
alertDate: function() {
alert(new Date().toUTCString());
}
}
var logModule = {
logName: function(name) {
console.log(name);
},
logDate: function() {
console.log(new Date().toUTCString());
}
}
return {
loadModules: function(moduleList) {
for(var i=0, l=moduleList.length; i<l; i++) {
try {
this[moduleList[i]] = eval(moduleList[i]);
} catch(e) {
throw("Module does not exist");
}
}
}
}
})();
LC.loadModules(['alertModules', 'logModule']);
The code below would add the alertModule and logModule objects to the LC object.
LC.loadModules(['alertModule', 'logModule']);
Inside the loadModules method, I'm looping through the array and using the following code to add the objects to LC:
this[moduleList[i]] = eval(moduleList[i]);
This works fine and I'm fairly sure it's secure (an error is thrown if the module doesn't exist) but is there a more elegant way of doing this? The only other way I can think to accomplish this would be to put the modules themselves inside an object so I could reference them more easily. Any other thoughts/ideas would be welcome!