Specify scope for eval() in JavaScript?

后端 未结 9 1267
心在旅途
心在旅途 2020-11-27 07:24

is there any way I can execute eval() on a specific scope (but NOT global)?

for example, the following code doesn\'t work (a is undefined on the sec

9条回答
  •  难免孤独
    2020-11-27 07:43

    you can use the "use strict" to contain the eval'ed code within the eval itself.

    Second, eval of strict mode code does not introduce new variables into the surrounding scope. In normal code eval("var x;") introduces a variable x into the surrounding function or the global scope. This means that, in general, in a function containing a call to eval every name not referring to an argument or local variable must be mapped to a particular definition at runtime (because that eval might have introduced a new variable that would hide the outer variable). In strict mode eval creates variables only for the code being evaluated, so eval can't affect whether a name refers to an outer variable or some local variable

    var x = 17;                                       //a local variable
    var evalX = eval("'use strict'; var x = 42; x");  //eval an x internally
    assert(x === 17);                                 //x is still 17 here
    assert(evalX === 42);                             //evalX takes 42 from eval'ed x
    

    If a function is declared with "use strict", everything in it will be executed in strict mode. the following will do the same as above:

    function foo(){
        "use strict";
    
         var x = 17;
         var evalX = eval("var x = 42; x");
         assert(x === 17);
         assert(evalX === 42);
    }
    

提交回复
热议问题