Why does eval() exist?

后端 未结 6 819
执笔经年
执笔经年 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:30

    Eval is actually a powerful feature and there are some things that are impossible to do without it. For example:

    1. Evaluate code received from a remote server. (Say you want to make a site that can be remotely controlled by sending JavaScript code to it?)
    2. Evaluate user-written code. Without eval, you can't program, for example, an online editor/REPL.
    3. Creating functions of arbitrary length dynamically (function.length is readonly, so the only way is using eval).
    4. Loading a script and returning it's value. If your script is, for example, a self-calling function, and you want to evaluate it and get it's result (eg: my_result = get_script_result("foo.js")), the only way of programming the function get_script_result is by using eval inside it.
    5. Re-creating a function in a different closure.

    And anything else you'd want to do that involves creating code on the fly.

    The reason it is considered "evil" is because it's classicaly used by novices to do things that the language can handle natively. For example, the code below:

    age_of_erick = 34;
    age_of_john = 21;
    person = "erick";
    eval("console.log('age_of_"+person+"')");
    

    And the code below:

    age = {erick:34, john:21};
    person = "erick";
    console.log(age["erick"]);
    

    Both do the same thing, except one parses a string, generates code from it, compiles into machine code and then runs, while the other reads a value from a hash, which is a lot faster.

提交回复
热议问题