The role of the Eval () function in JavaScript

Source: Internet
Author: User

Code highlighting produced by Actipro Codehighlighter (freeware) http://www.codehighlighter.com/-->, first of all, a simple understanding .eval can execute a string generation statement, similar to the SQL exec (). What are the use cases for eval? Sometimes we don't know what statements to execute in advance, and Eval comes in handy only when the conditions and parameters give you the idea of what to execute.            For example: We are going to do a function (), which is to enter the names of two objects in a Web page, and then the program joins the values of the two objects to output. functionoutput (A, b) {varTMPA,TMPB; Tmpa=Document.all.a.value; TMPB=Document.all.b.value; document.write (Tmpa+TMPB); } Output (' Input1 ', ' input2 '); This way you will be prompted with the error "DOCUMENT.ALL.A is not an object" and "document.all.b is not an object" when you execute it. The original JavaScript used a and B as the object name, how can you let JavaScript put the value inside a As object name? It's time to use eval and change the code to this:functionoutput (A, b) {varTMPA,TMPB; Tmpa=eval ("document.all.") +a+ ". Value"); TMPB=eval ("document.all.") +b+ ". Value"); document.write (Tmpa+TMPB); } Output (' Input1 ', ' input2 '); JavaScript then takes the value of a, B, and then runs with the previous document.all and the. Value, so that the values of INPUT1 and input2 can be removed smoothly. Read the basic understanding above what does eval mean then look at the following Understand the use of the Eval function in JavaScript by using the example in the DOM to replace the image in a little bit of progression? The eval () function JavaScript has a number of tips to make programming easier. One of them is the eval () function, which can execute a string as if it were a JavaScript expression. For a small example:varThe_unevaled_answer = "2 + 3"; varThe_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 a string in JavaScript"2 + 3"was actually carried out. So when you set the value of The_evaled_answer to eval ("2 + 3"JavaScript will understand and return the 2 and 3 and back to The_evaled_answer. This seems a bit silly, actually can make very interesting things. Using eval, for example, you can create functions directly from the user's input. This allows the program to change itself depending on time or user input, and with extrapolate, you can get amazing results. In practice, eval is seldom used, but you may have seen someone use eval to get objects that are difficult to index. One of the problems with the Document Object Model (DOM) is that sometimes it's painful to get the object you're asking for. For example, here's a function that asks the user which image to transform: Transform which image you can use the following function:functionSwapone () {varThe_image = prompt ("Change parrot or Cheese", "" "); varThe_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"; } together with these image tags: [img src= "/stuff3a/parrot.gif" name= "Parrot"] [img SRC= "/stuff3a/cheese.gif" name= "cheese"] Please note a few lines like this: The_image_object=Window.document.parrot; It puts an image object into a variable.            It seems a little strange, but it has no grammatical problems. But what happens when you have 100 images instead of two? You had to write a whole bunch of them.if-then-Else statement, if it can be like this:functionSwaptwo () {varThe_image = prompt ("Change parrot or Cheese", "" "); WINDOW.DOCUMENT.THE_IMAGE.SRC= "Ant.gif"; Unfortunately, JavaScript will look for names called the_image rather than what you want."Cheese" or "parrot"image, and you get the error message: "I haven't heard of an object named The_image."            Fortunately, Eval can help you get the object you want. functionSimpleswap () {varThe_image = prompt ("Change parrot or Cheese", "" "); varThe_image_name = "window.document." +The_image; varThe_image_object =eval (the_image_name); THE_IMAGE_OBJECT.SRC= "Ant.gif"; } If the user fills in the prompt box"Parrot", a string, Window.document.parrot, is created in the second row. Then the third line containing the eval means:"Give me the object Window.document.parrot"-that's the image you want. Once you have acquired the Image object, you can set its SRC attribute to ant.gif. A little scared? Don't.            In fact, this is very useful, and people often use it.            We often go to the function of eval in the middle of JavaScript, some people think that this function is very strange, can make some string function is very powerful when we need to turn the ordinary string into a concrete object, we will use this function The Eval function evaluates a string that is a numeric expression whose syntax is: eval (expr) Here expr is a string parameter that is evaluated. If the string is an expression, eval evaluates the value of the expression, and if the argument represents one or more JavaScript statements, the Eval executes the statements.            The Eval function can be used to convert a date from a format (always a string) to a numeric expression or a number. ==============================The function of the Eval function: The JavaScript code is interpreted first, and then it is used: Eval (codestring) codestring is included with Javas            The string for the Cript statement, compiled with the JavaScript engine after Eval. Note: Example: eval (id+ "_icon.src="/imgs/collapse_up.gif '"); The ID is the previously set parameter, and the string in double quotation marks is a reference that needs to be compiled:------------------------------------------------------------------- -------------function tophide (ID)//id indicates menu {if (top.topframeset.row                     s = = "31,*") {top.topframeset.rows = "86,*"; Eval (id + "_icon.src="/imgs/collapse_up.gif‘"); Eval (id +"_icon.alt= ' Collapse the Head '"); Head.style.display ="Block"} else {top.topframeset.rows ="31,*"; Eval (id +"_icon.src="/imgs/collapse_down.gif ' "); Eval (id+ "_icon.alt= ' Expand the Head '"); Head.style.display= "None"}} If you still don't understand in-depth understanding of the Eval function in JavaScript it's not so easy to find the right title for this article, huh? , the two purposes of this article are explained here: (1describes the use of the Eval function in JavaScript (2How to execute global code within a function& #9658first, the use of eval, the content is relatively simple, familiar can skip. The eval function receives a parameter s, and if S is not a string, it returns s directly. Otherwise, the S statement is executed.            If the S statement execution result is a value, this value is returned, otherwise undefined is returned. It is important to note that the object declaration syntax "{}" does not return a value and needs to be enclosed in parentheses to return a value, a simple example is as follows:varCode1= ' "a" + 2 ';//An expression            varCode2= ' {a:2} ';//StatementAlert (eval (code1));//' A2 'Alert (eval (code2));//->undefinedAlert (eval (' (' + Code2 + ') ');//->[object Object]As you can see, for an object declaration statement, it is only execution and cannot return a value. In order to return an object declaration statement such as a commonly used "{}", it must be enclosed in parentheses to convert it to an expression in order to return its value. This is one of the basic principles of AJAX development using JSON.            As you can see clearly in the example, the second alert statement outputs undefined, and the third one with parentheses outputs the object represented by the statement. & #9658now, the focus of this article is how to execute global code within a function. To illustrate this problem, let's look at an example:vars= ' Global ';//define a global variable            functionDemo1 () {eval (' var s= ' local ');            } demo1 ();    alert (s); //->globalIt is well understood that the DEMO1 function above is equivalent to:functionDemo1 () {vars= ' Local ';}, where a local variable s is defined.            So the final output is global, which is not a strange thing, after all, we can clearly distinguish between local variables and global variables. After a closer look, you can see the characteristics of the Eval function, which is always executed within the context variable space (also known as: Package, closure) that invokes it, whether it is a variable definition or a function definition, so the following code produces an undefined error:vars= ' function test () {return 1;} ';//a function definition statement            functionDemo2 () {eval (s);            } demo2 ();    Alert (test ()); //->error:test is not definedThis is because the test function is defined in the local space and can be accessed within the DEMO2 function, and is inaccessible outside.            In the actual Ajax development, sometimes we need to get the code from the server dynamically, to alleviate the problem of loading too much code one time, or some code is generated by JavaScript itself, want to use the Eval function to make it execute. But this kind of dynamic get code work is usually done within the function, such as:functionLoadcode () {varCode=GetCode ();            eval (code);            It can be seen that eval cannot be performed in the global space, which brings a lot of problems to development and has seen a lot of people depressed. But now I finally found a solution, hey, can also be compatible with IE and Firefox, the method is as follows:varx2={}//My namespace:)X2. Eval=function(code) {if(!! (Window.attachevent &&!)Window.opera)) {              //IEExecScript (code); }Else{              //Not ieWindow.eval (code); Now if you want to define global code within a function, you can call the X2.eval (code) method, an example is as follows:vars= ' Global '; functionDemo3 () {X2. Eval (' var s= ' local ');            } Demo3 (); alert (s); //' Local 'It is visible that the global variable s= "local" is redefined within the DEMO3 function. It is important to note that X2.eval does not return a value, and if the expression is evaluated, the system's eval function is used. X2.            The eval is designed to be used only for global code definitions. Actually see here, perhaps some people feel that the problem is too easy to solve the point, hehe, but found that this method is to need some luck and skill: (1for IE, the default already provides a function: ExecScript, which executes the code in the global space, only knows not many people. (2) for the Firefox browser, the Eval function is invoked directly in the caller's space, and if the call to Window.eval is executed in the global space. The person who knows is probably even less. After all, alert (eval==window.eval) return true! The feature of the Eval function in Firefox is really surprising, but it can also be found from the JavaScript specification: If value of the Eval property is usedinchAny -to-than a direct call (which is, and than by the explicit use of the IT name as an Id Entifier which is the memberexpressionincha callexpression), orifThe Eval property was assigned to, a Evalerror exception may be thrown. This means that the Eval function's execution is related to the caller, but does not say that it is executing the context. So IE and Firefox is the right thing to say, you know the solution is good

Original: http://www.cnblogs.com/scy251147/archive/2010/10/12/1849253.html

The role of the Eval () function in JavaScript

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.