JavaScript Learning Summary of the unwanted eval function and with statement instance detailed _javascript skills

Source: Internet
Author: User
Tags eval html form

Front.

Eval and with are often abandoned as if their existence were errors. In CSS, the table is abandoned, in the Web page only use tables to display data, rather than do layout, can be dismissed as irregular, overkill. What about Eval and with? The eval () function and the WITH statement are described in detail in this article

Eval

Defined

Eval () is a global function in which JavaScript interprets strings that are run by JavaScript source code through eval ()

var result = eval (' 3+2 ');

Usage

Eval () has only one parameter, and if the incoming argument is not a string, it returns this argument directly. If the argument is a string, it compiles the string as a JavaScript code. If the compilation fails, a syntax error (SYNTAXERROR) exception is thrown. If the compilation succeeds, the code is executed and the value of the last expression or statement in the string is returned, and if the last expression or statement has no value, the undefined is eventually returned. If the string throws an exception, this exception passes the call to Eval ()

var num = 1;
var str = ' Test ';
Console.log (eval (num));//1
Console.log (eval (str));//referenceerror:test is not defined 
var strLong1 = ' var x = 1;var y = 2; ';
Console.log (eval (strLong1), x,y);//undefined 1 2
var strLong2 = ' var x = 1; x + +; ';

Scope

Eval () uses the scope environment of the variable that invoked it. That is, it looks for the value of a variable and the actions that define new variables and functions exactly the same as the code in a local scope

var b = 2;
function foo (str,a) {
eval (str);
Console.log (a,b);
}

Alias

When invoked through an alias, Eval () executes its string as the top-level global code. The code that executes may define new global and global functions, or assign values to global variables, but cannot use or modify local variables in functions

var geval = eval; 
var x = ' global ', y = ' global '; 
function f () {
var x = ' local ';
Eval (' x + + changed '; ');
return x;
}
function g () {
var y = ' local ';
Geval (' Y + + changed '; ');
return y;
}
Console.log (f (), x);//localchanged Global

Attention The Ie8-Browser calls eval () by alias and the result of a normal call to Eval () is the same

Side effects

The JavaScript interpreter carries out a lot of code analysis and optimization. The problem with Eval () is that the code used for dynamic execution is usually not parsed, and the interpreter cannot optimize it, which can cause performance degradation

Similar to eval (), there are settimeout (), SetInterval (), new function (), and so on, which can be executed dynamically while the program is running as a string parameter. The benefits of this implementation mechanism do not offset their performance losses, so you should try to avoid using

Strict mode

Because the eval () function is too powerful, strict mode restricts it strictly

"1" Cannot create a variable or function through the eval () function, but can query and change its value

' Use strict ';
Eval (' var x = 1; ');
Console.log (x);//referenceerror:x is isn't defined
' use strict ';
var x = 1;
eval (' x = 2; ');

' 2 ' disables the use of eval as an identifier

' Use strict ';

With

The purpose of defining a with statement is primarily to simplify the work of writing the same object multiple times

The With statement adds object to the head of the scope chain, executes the statement, and finally restores the scope chain to its original state

With (object) {
statement;
}

Role

The With statement is usually used to simplify code writing when the object nesting level is very deep. In essence, a new lexical scope is created by treating the object's properties as identifiers in the scope by handling the references of an object as scopes.

In client JavaScript, you might use an expression such as the following to access elements in an HTML form

 
 

If this expression appears more than once in your code, you can use the WITH statement to add the form object to the top of the scope chain

With (Document.forms[0]) {
name.value = ';
Address.value = ';
Emai.value = ';

This approach reduces the amount of input and no longer adds the document.forms[0] prefix for each property name. This object is temporarily mounted on the scope chain, and when JavaScript needs to parse an identifier such as address, it automatically looks in the object

[Note The]with statement provides a shortcut to read an object's properties, but it does not create an object's properties

If object o has an attribute x, then the following code assigns this property to 1

var o = {x:0};
With (o) x = 1;

If no attribute x is defined in O, the following code is identical to the code x=1 without the WITH statement. This is because the LHS query for the variable x and assigns 1 to it

var o = {};
With (o) x = 1;
Console.log (o.x);//undefined

Side effects

Like Eval, the JavaScript code for the WITH statement is very difficult to optimize, and also makes debugging code difficult, and is more slowly compared to code that does not use the WITH statement

Furthermore, if the WITH statement is not appropriate, it is possible to cause variable leakage and pollute the global scope

var x = 1;
var o = {};
With (o) {
x = 2;
}
Console.log (x);//2

Strict mode

In strict mode, disable the WITH statement

Syntaxerror:strict mode code may isn't include a with statement
' use Strict ';
var o = {};
With (o) {
x = 2;
}

At last

Using eval and with and with will make it impossible for the engine to optimize scope lookup at compile time, resulting in degraded performance and slow code execution. Because Eval and with are rarely used in practice, the restrictions in strict mode have little impact on us. Just like the Ministry of Foreign Affairs issued a proclamation one day, our country no longer issued visas to Jamaica, although Jamaica has heard, but most people in this life may not go back, so it doesn't matter. Similarly, eval and with are not to be abandoned, it doesn't matter

The above is a small set up to introduce the JavaScript learning summary of the Eval function and with statement examples, I hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.