eval introduction
---eval is a method of the global object prototype in the ECMA definition;
---The parameter accepted by eval is js code in string format. This string will be executed by the execution engine (remember what I said in 'Advanced Programming', create a new execution engine at this time), and then return the result to The location where eval is called.
<!DOCTYPE html> <html> <head> <title>eval学习</title> <script type="text/javascript"> /* eval("表达式");执行表达式语句 eval("("+javascript类型+")");转为javascript对象 */ var jsonObj={"name":"ljl","data":123};//json,是javascript的对象 var jsonString='{"name":"ljl","data":123}';//javascript的string类型,字符串内容符合json格式的样式 var objType=eval("("+jsonString+")");//通过eval函数将json字符转为javascript对象 alert( typeof jsonString);//string alert( typeof objType);//obj alert(eval(123));//123 alert(typeof eval("("+123+")"));//number var x=2; var y=eval('x+1');//执行 2+1 表达式 alert('y= '+y);//3 </script> </head> <body> </body> </html>
Additional: Summary
eval is one of the dynamic features of js. It can directly execute js programs and return results. A common use is to restore json data to js objects;
However, because it can dynamically change the context object at runtime, it brings the risk of injection attacks;
When using it, pay attention to how eval understands the syntax of strings. A common problem is the 'braces' problem