Dynamic Loading with eval()

03 Mar 2008

CodeI may not be able to explain how cool this is, but I’m going to try.

Right now I’m working on a replacement for the nasty VBScript I posted a while back that updates the software installed on the computers at work. Sure, the script did it’s job but it wasn’t pretty to look at and updating it or adding new software is a pain in the arse.

To make my new and improved version, I wanted to redesign my installer/updater code in a nice, modular, object-oriented, easy to update manner. I devised a modular solution where I would write one main script that would perform all the heavy lifting, with the specifics of each application provided by simple scripts that could be added, removed, and updated with ease.

The main script scans a directory looking for all files that end in “.app.js,” loads them up, and executes the commands found within. Each .app.js file provides a single class, with the same name as the first part of the file name (so foo.app.js would provide a class called foo). This class in turn provides a set of properties that the main script can use to perform actions (such as checking versions, upgrading software, removing software… you get the idea).

Now the tricky part? You have no idea what the class names are prior to run time. So you can’t create new objects using “var bar = new foo().”

I’d learned about the JScript “eval()” statement a while back, which I used extensively for simulating C’s “#include” statement. The cool thing about it is that eval() performs JScript execution on a text stream… so to perform dynamic loading with eval(), I simply used concatenation to produce a string like such:

var callString = “new ” + methods.call[index] + “()”;

and then evaluated the string:

var newObject = eval(callString);

And it works like a charm! Now I can run a loop over my array of class names, create new objects, and perform all my other nifty little tasks. It looks simple, but I had to contemplate this for a second before the light bulb flashed on… I’m sure someone out there has already done this, been just as excited as me, and posted about it on their own blog. However, this is the solution I came up with off the top of my head without the assistance of any Google searches, so I’m going to be happy and post about it here before I ever check Google!