|
|
|
Abstract: Todays article discussed the built in eval function which lets you define and execute code on the fly. In complex and extremely rare cases, a programmer may not know in advance what code should be executed. Depending on values of different variables a particular statement may need to be executed at run time. This is where eval function comes in.
Although most of the functions in JavaScript are actually methods, eval is different; it is a top-level function defined in JavaScript. It doesn't belong to any object.
This function accepts a single argument: a string that contains the code to be executed. The following example domonstrates string creation and evaluation using this function. <html>
This simple code says a lot. We define a string variable, namely stmt and assign it JavaScript code for displaying an alert message. This assignment is a normal operation; i.e., there are no effects other than changing the stmt's value. Next comes the call to eval function. We pass it on our string. The web browser first tries to parse the string and understand what it means. It then carries out the task, which, in our case, is to display an alert message. Note that the value of the stmt variable can be given at run time. It may even come from a text box.
Very few languages allow polymorphic code - code that can change itself. Though, the usage is rare but this function fits very nicely in situations where you execute code depending on the input from the user and multiple if's become increasingly complex. Go To Page: 1
The copyright of the article The eval() Function in JavaScript is owned by . Permission to republish The eval() Function in print or online must be granted by the author in writing.
|
|
|
|
|
|
|
|