The difference between the eval of JavaScript and the new function

Source: Internet
Author: User

When you have to execute a string as code, many people first think of using eval, but in fact, using the new function is more secure.    

Why is it safe? Look at an example.

<script> var a = 1;   Eval ("Var a=2;");    Change the current domain variable a alert (a); New Function ("Var a=3;")   (); Do not change the current scope of the variable alert (a);</script>

eval can affect the current scope and all the variables of the parent scope, and the new function is run within a separate function, and his parent scope is window instead of the current scope. Let's look at another example.

<script> var a = 1;   Eval ("Var a=2;");    Change the current domain variable a alert (a); New Function ("Var a=3;")   (); Do not change the current scope of the variable alert (a);</script>



one might say that the new function is isolated from the current scope. So how do I get a string as a value after the code runs? For example, a classic application that transforms a JSON string into an object literal

such as var B = ' {' A ': ' B '} ' You can add a return directly, such as var C = new Function ("Return" +b) (); So C is an object of the same format.


This article is from the "Leeturn" blog, make sure to keep this source http://9476439.blog.51cto.com/9466439/1567361

The difference between the eval of JavaScript and the new function

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.