More Fun With JavaScript - Nested Evals
Posted by Greg Bulmash in Techno Thoughts, Web Programming, tags: javascriptSo, the way I learn a new programming skill is I get an idea for a program I need to learn the language (or improve my knowledge of it) to create. Then as I learn the things I need to know, I toy with various ideas and do little experiments just to see what happens or what's possible.
This time I wanted to know if I could get a string name passed, then use it in some function using the eval() function to get its value. For example
var steve="blue";
var blue="danny";
alert(eval(steve));
Now, if it was just alert(steve), the result would be an alert window with the message "blue". But because eval is evaluating the content of "steve" as code... The value of "steve" is "blue" and the value of the variable "blue" is "danny", so alert(eval(steve)) generates an alert window with the message "danny".
But the cool thing is that you can nest evals...
<script type="text/javascript">var steve="blue";
var blue="danny";function gotoit(sedley){
alert(eval(eval(sedley)));
}</script>
<a href="javascript:gotoit('steve');">Run The Dang Script</a>
In this case, the value of sedley is "steve", which evaluates to "blue", which has the value of "danny".
I know, sort of pointless, but it was neat to me and I thought I'd share.


Entries (RSS)
You're extremely self-learned. :p
There's more to JS. You can use strings to access variable fields of objects using array brackets:
this.elephant = "cookiedough"; var key = "elephant"; alert (this [key]);('this' is a keyword referring to the current object in context, at the top it's going to be 'window')
'eval' is usually avoided because it can introduce security holes. Of course it doesn't matter at all clientside.
Ow...my brain.