The previous words
Eval and with are often disliked, as if their existence is a mistake. In CSS, tables are disliked and only use tables to display data on web pages, rather than layout, may be denied as irregular and overcorrect. So what is the situation about eval and with? This article will introduce the eval() function and with statement in detail
eval
definition
eval() is a global function. JavaScript uses eval() to explain the running string composed of javascript source code.
var result = eval('3+2');console.log(result,typeof result);//5 'number'usage
eval() has only one parameter. If the passed parameter is not a string, it directly returns this parameter. If the parameter is a string, it will compile the string as javascript code. If compilation fails, a syntax error (syntaxError) exception is thrown. If the compilation is successful, 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, it will eventually return undefined. If a string throws an exception, the exception will pass the call to eval()
var num = 1;var str = 'test';console.log(eval(num));//1console.log(eval(str));//ReferenceError: test is not defined var strLong1 = 'var x = 1;var y = 2;';console.log(eval(strLong1),x,y);//undefined 1 2var strLong2 = 'var x = 1; x++;';console.log(eval(strLong2),x);//1 2
Scope
eval() uses the variable scope environment that calls it. That is, it looks for the value of a variable and defines the operation of a new variable and function and the code in the local scope.
var b = 2;function foo(str,a){eval(str);console.log(a,b);}foo('var b = 3;',1);//1 3Alias
When called through an alias, eval() will execute its string as the top-level global code. Executed code may define new global variables and global functions, or assign values to global variables, but cannot use or modify local variables in the function.
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 globalconsole.log(g(),y);//local globalchanged[Note] IE8-The browser calls eval() through an alias and calls eval() normally the same result.
side effect
The javascript interpreter performs a lot of code analysis and optimization. The problem with eval() is that the code used for dynamic execution is usually not analyzed, so the interpreter cannot optimize it, which will lead to performance degradation
Similar to eval() are setTimeout(), setInterval(), new Function(), etc. These functions can be executed dynamically when the program is run using strings as parameters. The benefits of this execution mechanism cannot offset its performance losses, so you should try to avoid using it.
Strict mode
Because the eval() function is too powerful, the strict mode strictly restricts it
【1】Variables or functions cannot be created through the eval() function, but their values can be queried and changed
'use strict';eval('var x = 1;');console.log(x);//ReferenceError: x is not defined'use strict';var x = 1;eval('x = 2;');console.log(x);//2【2】Unable to use eval as an identifier
'use strict';var eval = 10;//SyntaxError: Unexpected eval or arguments in strict mode
with
The purpose of defining with statements is to simplify the work of writing the same object multiple times.
The with statement adds object to the head of the scope chain, then executes the statement, and finally restores the scope chain to its original state.
with(object){ statement;}effect
When the object nesting level is deep, with statements are usually used to simplify code writing. In essence, it is processed by treating an object's reference as a scope and using the object's attributes as identifiers in the scope, thus creating a new lexical scope
In client javascript, an expression like the following may be used to access elements in an HTML form
document.forms[0].address.value
If such an expression appears multiple times in the code, you can use the with statement to add the form object to the top level of the scope chain
with(document.forms[0]){name.value = '';address.value = '';emai.value = '';}This method reduces a lot of input without having to prefix document.forms[0] for each property name. This object is temporarily mounted on the scope chain. When JavaScript needs to parse identifiers such as address, it will automatically search in this object.
[Note] The with statement provides a shortcut to read the properties of an object, but it cannot create properties of an object
If object o has an attribute x, then the following code assigns the attribute value to 1
var o = {x:0};with(o) x = 1;console.log(ox);//1If no attribute x is defined in o, the following code is exactly the same as the code x=1 that does not use the with statement. This is because the LHS query is performed on the variable x and 1 is assigned to it
var o = {};with(o) x = 1;console.log(ox);//undefinedconsole.log(x);//1side effect
Similar to eval, the javascript code of the with statement is very difficult to optimize, and it also causes difficulties in debugging the code. It is slower than code that does not use the with statement.
Moreover, if the with statement is inappropriate, it may cause variable leakage and pollute the global scope.
var x = 1;var o = {};with(o){x = 2;}console.log(x);//2console.log(ox);//undefinedStrict mode
In strict mode, the use of with statements is prohibited
//SyntaxError: Strict mode code may not include a with statement'use strict';var o = {};with(o){x = 2;}at last
Using eval and with makes it impossible for the engine to optimize scope lookups at compile time, resulting in performance degradation and slower code running. Because eval and with are rarely used in actual work, the restrictions under strict mode have little impact on us. Just like the Ministry of Foreign Affairs issued an announcement one day that our country will no longer issue visas to Jamaica. Although we have heard of Jamaica, most people may not go there once in their lives, so it doesn’t matter. Similarly, it doesn't matter if eval and with are disliked or not
The above is a detailed explanation of the JavaScript learning summary that the editor introduced to you about is despised eval function and with statement examples. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!