JavaScript Basics Avoid using eval () (006)

Source: Internet
Author: User

Many people think that the eval () method is evil (evil). This method can be used to execute arbitrary strings as JavaScript code. We should not use the Eval () method as much as possible. For example, you can use square brackets to get the value of an object property:

Antipatternvar property = "Name", Alert (eval ("obj." + property);//Preferredvar property = "name"; alert (Obj[property) );

In addition, JavaScript's setinterval () and settimeout () methods have similar problems. You should also avoid passing strings as arguments to these methods:

Antipatternssettimeout ("MyFunc ()"), SetTimeout ("MyFunc (1, 2, 3)", +//Preferredsettimeout (MyFunc, 1000); SetTimeout (function () {    myFunc (1, 2, 3);}, 1000);

The new function () can also accept the string as a parameter, but this should also be avoided. The difference between new function () and eval () is that the variables in the code executed by eval () will "become" global variables, but new function () is not.

Console.log (typeof un);    "Undefined" console.log (typeof deux);  "Undefined" console.log (typeof trois); "Undefined" var jsstring = "var un = 1; Console.log (un); "; eval (jsstring); Logs "1" jsstring = "var deux = 2; Console.log (deux); "; New Function (jsstring) (); Logs "2" jsstring = "var trois = 3; Console.log (trois); ";( function () {    eval (jsstring);} ()); Logs "3" Console.log (typeof un);    "Number" Console.log (typeof deux);  "Undefined" console.log (typeof trois); "Undefined"

In addition, the string code in eval () can access global variables in the program, while the new function does not. It is important to note that the function and new function effects are identical:

(function () {    var local = 1;    Eval ("local = 3; Console.log (local) "); Logs 3    console.log (local);//Logs 3} ());(function () {    var local = 1;    Function ("Console.log (typeof local);") (); Logs undefined} ());

JavaScript Basics Avoid using eval () (006)

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.