Why does eval() exist?

后端 未结 6 817
执笔经年
执笔经年 2020-12-09 01:49

Many programmers say it is a bad practice to use the eval() function:

When is JavaScript's eval() not evil?

6条回答
  •  长情又很酷
    2020-12-09 02:26

    There's a research publication exacty on this topic:

    The Eval That Men Do -- A Large-scale Study of the Use of Eval in JavaScript Applications
    Mirror on Wayback Machine

    It is to me the most comprehensive answer to this question to date.

    Quote from the abstract:

    We have recorded the behavior of 337 MB of strings given as arguments to 550,358 calls to the eval function exercised in over 10,000 web sites.

    Amongst other, they identified 9 categories of recurring eval:

    1. JSON - A JSON string or variant.
    2. JSONP - A padded JSON string.
    3. Library -One or more function definitions.
    4. Read - Read access to an object’s property.
    5. Assign - Assignment to a local variable or object property.
    6. Typeof - Type test expression.
    7. Try - Trivial try/catch block.
    8. Call - Simple function/method call.
    9. Empty - Empty or blank string.

    A snippet from the conclusion (which is too long to be quoted entierly):

    [...] While many uses eval were legitimate, many were unnecessary and could be replaced with equivalent and safer code. We started this work with the hope that it would show that eval can be replaced by other features. Unfortunately our data does not support this conclusion.[...]

    A paper well worth reading.

提交回复
热议问题