Oliver Nassar

Dynamic Variables Assignment?

August 07, 2009

In JS, I ran into a problem where I needed to create a shortcut string, and then turn that string's value into a reference to a different object.

So for example, I create a string called 'oliver' under the variable shortcut like so:

var shortcut = 'oliver';

Then I have a bunch of other code in my framework, and to access any of it, I would write something like:

FRAMEWORK.doSomething();

I wanted the framework's name space to be preserved (so that I could easily upgrade/update it without affecting any code), but I wanted to be able to use my shortcut handle to access the framework, such that writing the following would work as well:

oliver.doSomething();

This led me to the use of eval to run a js command in js itself to get the assignment/reference working properly like so:

eval(shortcut+' = FRAMEWORK');

This worked really well and met exactly what I was trying to do, but I'm always hesitant to use eval. I've heard terrible things about it's security and performance (although most ajax is based on this function). I'll look into it and update the post if I find anything, but for the mean while, this has helped me do what I was trying to. It allows me to write really general client side framework code that can then be extended easily into a new namespace without any conflicts. Very powerful stuff.

When I search for it on google, it didn't come up right away. My search terms (hopefully writing this in the post will help someone else) were: dynamic javascript variable assignment.

ps. The picture is supposed to represent a 'shortcut'. not the best fit I don't mind saying.

Update

window[name] = reference is the winner. I don't know why it escaped me before. This should prevent the use of eval and will allow you to dynamically create variables in the window scope.