Eval function
Function: First explain the JavaScript code, and then execute it
Usage: Eval (codestring)
Codestring is a string containing JavaScript statements that are compiled using the JavaScript engine after Eval.
Example 1: Execute script with eval
var the_unevaled_answer = "2 + 3";
var the_evaled_answer = eval ("2 + 3");
Alert ("The un-evaled answer is" + The_unevaled_answer + "and the evaled answer is" + the_evaled_answer);
If you run this eval program, you will see that the string "2 + 3" in JavaScript is actually executed. So when you set the value of The_evaled_answer to eval ("2 + 3"), JavaScript will understand and return 2 and 3 and back to The_evaled_answer.
This may seem a bit silly, but it can actually do very interesting things. Like using eval, you can create a function directly from the user's input. This allows the program to change depending on the time or user input, and you can get amazing results by extrapolate.
Example 2: An object obtained through eval
Implementation: A function that asks the user which image to transform
Non-eval implementation script:
function Swapone ()
{
var the_image = prompt ("Change parrot or Cheese", "");
var the_image_object;
if (the_image = = "Parrot")
{
The_image_object = Window.document.parrot;
}
Else
{
The_image_object = Window.document.cheese;
}
THE_IMAGE_OBJECT.SRC = "Ant.gif";
}
Along with these image tags:
Script for eval implementation:
Function simpleswap ()
{
var the_image = prompt ("Change parrot or cheese "," ");
var the_image_name = "Window.document." + the_image;
var the_image_object = eval (the_image_name);
the_image_object.src = "Ant.gif";
}