Home >Web Front-end >JS Tutorial >Summary of usage examples of eval and with in javascript_javascript skills
The examples in this article describe the usage of eval and with in javascript. Share it with everyone for your reference, the details are as follows:
We all know the scope mechanism of JavaScript, but with and eval sometimes "destroy" our conventional understanding of scope. Let’s summarize the usage of eval and with with reference to online resources and your own understanding.
1. eval
1. eval function: treat a string as a js expression to execute it.
2. Syntax: eval(strScript) Note: The parameter strScript is required
3. Instructions for use
(1) It has a return value. If the parameter string is an expression, the value of the expression will be returned. If the parameter string is not an expression and has no value, then "undefined" is returned.
(2) When the parameter string is executed as code, it is related to the context in which the eval function is called, that is, the variables or function calls that appear in it must be available in the context in which eval is called.
4. Example:
function $(s) { if (document.getElementById) { return eval('document.getElementById("' + s + '")'); } else { return eval('document.all.' + s); } } //eval,这个比较常用 var myTest = function() { return "eval test"; }; function evalTest() { //简单数据 alert(eval("1+1")); //2 alert(eval("'a'+1")); //a1 alert(eval("1+'a'")); //1a alert(eval("parseInt('a'+1)")); //NaN alert(eval("parseInt(1+'a')")); //1 alert(eval("true")); //true alert(eval("0==false")); //true alert(eval("1==undefined")); //false alert(eval("isNaN(undefined)")); //true //函数和对象 alert(eval("this")); //[object] alert(eval("typeof(this)")); //object alert(eval("typeof(test)")); //undefined alert(eval("evalTest")); //这个显示当前函数的定义语句细节,包含注释 //alert(eval("evalTest()")); //调用自己并执行,这个会有大问题啊! alert(eval("typeof(evalTest)")); //function //其他 var tmpFunc = "{a:1}"; alert(eval(tmpFunc)); //1 alert(eval("(" + tmpFunc + ")")); //[object object] alert(eval("tmpFunc")); //{a:1} //alert(eval("tmpFunc()")); //脚本错误 alert(myTest()); eval("alert(myTest())"); //和上面等价 alert(eval(myTest)); alert(eval("myTest")); //和上面等价 //form里的一个input,id=txtUserName eval("$('txtUserName').value='jeff wong';"); //等价于 $('txtUserName').value = 'jeff wong'; eval("alert( $('txtUserName').value);"); } evalTest();
5, eval and scope
(1) Classic code analysis
a. Common
var str = "global"; function test() { alert(str); //undefined var str = "local"; } test(); alert(str); //global
Analysis: As we expected, the specified value is obtained. The results of str in the test function without var and with var declaration are also different. Readers can verify by themselves.
b, eval instead of directly declaring variables
var str = "global"; function test() { alert(str); //?? eval("var str='local';");//会像我们预期的那样吗? //var str = "local"; alert(str); //这里又是什么结果? } test(); alert(str); //??
Analysis: Compared with the writing method in a, we just use the eval statement in the test function to replace the sentence that directly declares var to define the variable and just alert at the end. The results are very different.
(2) eval defines global code
a. The eval function that is compatible with IE and FF and defines global code
var nav = new Object(); //通用eval函数 nav.Eval = function(jsCode) { if (document.all) //IE下是execScript execScript(jsCode); else window.eval(jsCode); //FF下是window.eval }
For IE browser, the function execScript is used to execute code in the global space.
For the Firefox browser, if the eval function is called directly, it will be executed in the caller's space; if window.eval is called, it will be executed in the global space; but the return value of alert(eval==window.eval) is true, which is strange ff.
b. Call the test code of a
var nav = new Object(); //通用eval函数 nav.Eval = function(jsCode) { if (document.all) //IE下是execScript execScript(jsCode); else window.eval(jsCode); //FF下是window.eval } function test() { nav.Eval("var str = 'global';"); //这里声明变量str,在外面的函数中可以调用变量 nav.Eval("var tmpFunc = function(){alert('global function');};"); //这里声明函数变量tmpFunc,在外面的函数中可以调用函数 alert(str); //global tmpFunc(); //global function } test(); alert(str); //global (调用nav.Eval函数声明的全局变量) tmpFunc(); // global function (调用nav.Eval函数声明的全局函数)
Analysis: Through the code in b, you may have discovered an obvious inconvenience of eval defining global code, that is, for global code, js smart prompts (here vs, and other tools may also) are completely lost. Prompt function. From this, you will definitely ask, if a lot of global code is defined in the program through eval, will its maintainability be too low? My opinion is that I agree with the summary on the Internet and use eval less. After all, ready-made tools cannot provide good prompts, and programmers' eyesight is often not that good.
2. with
1. with statement: Specify a default object for one or a group of statements, usually used to shorten the amount of code that must be written in a specific situation .
2. Grammar: with (273238ce9338fbb04bee6997e5552b95) fa7ef95fdb8b7324b4f19dcbb8e23063
with (object)
statements
(1) Parameter object: new default object;
(2) statements: one or more statements, object is the default object of the statement.
3. Example:
function withTest() { with (document) { //document的重复使用 writeln("Hello,"); writeln("it's a with keyword test!"); } with (Math) { //Math的重复使用 alert(random()); alert(abs(-10)); } } withTest();
4. with will temporarily modify the scope chain
function withTest() { var userName = "jeff wong"; //暂时修改作用域链 with (document) { writeln("Hello,"); writeln(userName); }//with内的语句执行完之后,作用域链恢复原状 alert(userName); } withTest();
Analysis: When the function withTest is defined, the scope chain of withTest is determined. We temporarily think that the top of this scope chain is the window object. When withTest is executed, the js engine generates a call object (calling object) and add it to the end of the scope chain (after the window object). When the statement runs to with(document), a new scope will be generated (in essence, this scope is the same as the scope of an ordinary function, except that However, after the with clause is executed, the scope disappears) and is added to the end of the scope chain, so when searching for variables within with, priority will be given to the with (document) scope of this chain. , then search from the call object of withTest, and finally search for window. After the statement within with is executed, the scope chain is restored to its original state (the scope generated by with(document) is moved out of the scope chain).
ps: with is not recommended because it requires operating the scope chain (moving in and out of the scope), which results in low execution efficiency.
I hope this article will be helpful to everyone in JavaScript programming.