thesonglessbird
thesonglessbird

Reputation: 570

Alternative to using eval?

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!

Upvotes: 0

Views: 91

Answers (1)

cezar
cezar

Reputation: 56

Try this: http://jsfiddle.net/PUgM7/2/

Instead of referencing those "private" variables with eval() you could have a hash of modules.

var modules = {
  alertModule: { .. },
  logModule: { ... },
}

You could expand on this and add extra functionality like dynamically registering modules with another public method, say addModule.

return {
  addModule: function(name, newModule) {
    modules[name] = newModule;
  },
  loadModules: function() { ... } 
}

Upvotes: 1

Related Questions