Dynamic Code Execution
It may be hard to
believe, but JavaScript support dynamic method invocation and, any code
execution, for that matter with eval() method. This method evaluates
a string of valid JavaScript and executes it.
This allows us to
pass a name of the method as a string and have this function invoke
our method. Dynamic method invocation may free you from having to write
a bunch of if..else statements and provide a way to program a lot of
interesting dynamic things.
Basically, your
program may write the code for itself and execute it. Or your users
may provide you with the code and you can execute it on the fly. Or
you can easily let your users build custom expressions. Wow! Imagine
the possibilities!
Example 1:
Type in any JavaScript
code and click the button to execute it. You can try typing "alert("My
message") or window.open("http://www.yahoo.com"). Also
try to type in myFunction("show"). This will do the same as
alert(), but will call the method myFunction() defined on this page
to do that.
Example 2:
Type in any valid
mathematical expression in input box, click compute and see the results.
You may even include variables. The value displayed in result will be
the assignment value of the last expression. Example: x=1; y=5; z=x+y;
Result will be 6.
|