Use of JavaScript eval () Functions

Source: Internet
Author: User
Tags javascript eval

When I was a beginner at JS, I knew about this function, but I never knew about its purpose. I always kept one eye closed and one eye closed. This time I will take a deeper look at the role of this function.

The function of eval is actually very simple. It is to pass a string to the JS interpreter. The Javascript interpreter interprets the string as Javascript code and runs it. The syntax is eval (string), and string is required. The string to be calculated, which contains the JavaScript expression to be calculated or the statement to be executed. Returns the string value (if any ).

This method only accepts the original string as the parameter. If the string parameter is not the original string, this method will be returned without any change. Therefore, do not pass a String object as a parameter for the eval () function.

If you try to override the eval attribute or assign the eval () method to another attribute and call it through this attribute, ECMAScript can throw an EvalError exception.

If the parameter does not contain valid expressions and statements, a SyntaxError exception is thrown. If eval () is illegally called, an EvalError error is thrown. If the Javascript code passed to eval () generates an exception, eval () will pass the exception to the caller.

The simplest example is as follows:

<script type="text/javascript"> eval("alert(1+1)");<script>

It is very easy to interpret the string into JS Code and execute it. Pop-up 2.

Of course, the above example is just a toy. In reality, no one will be so stupid. I think the most basic eval functions should be in the DOM. For example, if we have div1, div2, and div3. when getElementByID is used, our ID cannot be obtained. The simplest way is to use eval to concatenate such a program in the for loop. For example:

<script type="text/javascript">for (var loop = 1; loop < 10; loop++)     { eval('document.getElementById("div"+loop).innerHTML="123"'); }<script>

After the basic usage is complete, I believe everyone is still interested in this function. If this function only has such usage, it will be too boring. Let's take a look at the eval () function.

Let's start with the eval scope. Let's first look at such a function:

<script type="text/javascript">eval("var i=3");alert(i);<script>

The code is very simple, and 3 is displayed. Next, compare the Code:

<script type="text/javascript">var test = function () { eval("var i=3"); alert(i);}test();alert(i);<script>

The result is 3 first, and then undefined.

Note: The code dynamically executed by the eval () function does not create a new scope, and its code is executed in the current scope. Therefore, the eval () function can use this, argument, and other objects in the current scope.

In IE, a function that is very similar to eval () is supported: execScript (). We can write simple code.

<script type="text/javascript">var test = function () { execScript("var i=3"); alert(i);}test();alert(i);<script>

The result shows 2 3 s, which shows the features of the execScript function. First, it is similar to eval and can interpret the string as JS Code and execute it, however, its scope is not the current scope, but the global scope. When we put the above Code on Firefox and Google browsers and try: the code on execScript on Firefox is invalid, it also indicates a problem, the browser compatibility of execScript code is problematic.

So how can we summarize the "advantages" of these two functions, that is, global + browser compatibility. I searched the internet and gave a summary, probably like this:

<script type="text/javascript">var StrongEval = function (code) { if (window.navigator.userAgent.indexOf("MSIE") >= 1)     { execScript(code); } if (window.navigator.userAgent.indexOf("Firefox") >= 1)     { window.eval(code); } else     { execScript(code); }};var Test = function () { StrongEval("var i=3");}Test();alert(i);<script>

In this way, we can be perfectly compatible with FF and IE. The essential code is that eval and window. eval are not equivalent in FF, which is a wonderful thing.

In addition, we can also use eval + with to implement some odd sex techniques.

In general, we can write such code:

var obj = function () { this.a = 1; this.b = 2; this.c = 5; this.fun = function ()     { this.c = this.a + this.b; }};var o = new obj();o.fun();alert(o.c);

Or

var obj = {a: 1, b: 2, c: 5, fun: function ()     { this.c = this.a + this.b; }}

Or the following code is used:

var obj = function () { this.a = 1; this.b = 2; this.c = 5;};obj.prototype.fun = function () { this.c = this.a + this.b;}var o = new obj();o.fun();alert(o.c);

In any case, are you bored with this? Let's take a very different approach, so that at least we may feel a little more comfortable.

<script type="text/javascript">var funtemp = function () { c = a + b;}var obj = { a: 1, b: 2, c: 5};var fun;with (obj) { eval("fun = " + funtemp);}fun();alert(obj.c);<script>

However, Eval is rarely used in general cases and we can avoid using it.

Related Article

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.