Specify scope for eval() in JavaScript?

后端 未结 9 1259
心在旅途
心在旅途 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:49

    Create the variables you want to exist in your scope as local variables in a function. Then, from that function, return a locally-defined function that has a single argument and calls eval on it. That instance of eval will use the scope of its containing function, which is nested inside the scope of your top level function. Each invocation of the top level function creates a new scope with a new instance of the eval function. To keep everything dynamic, you can even use a call to eval in the top level function to declare the variables that will be local to that scope.

    Example code:

    function makeEvalContext (declarations)
    {
        eval(declarations);
        return function (str) { eval(str); }
    }
    
    eval1 = makeEvalContext ("var x;");
    eval2 = makeEvalContext ("var x;");
    
    eval1("x = 'first context';");
    eval2("x = 'second context';");
    eval1("window.alert(x);");
    eval2("window.alert(x);");
    

    https://jsfiddle.net/zgs73ret/

提交回复
热议问题