Using eval() to set global variables

后端 未结 3 1001
耶瑟儿~
耶瑟儿~ 2020-12-21 00:12

My code to set a global variable using eval is not working. It\'s as if the assignment is not called at all, but no script errors occur.



        
相关标签:
3条回答
  • 2020-12-21 00:50

    I wouldn't recommend setting global variables, but if you absolutely have to, use the window object:

    window['x'] = 1;
    
    0 讨论(0)
  • 2020-12-21 01:01

    Eval runs locally, you're setting a local variable.

    To set a global variable, remove var;

    <script type="text/javascript">
    
        $(function() {
    
            setTimeout(function() {
                eval('x = 1;');
                alert(x);
            }, 0);
        });
    </script>
    
    0 讨论(0)
  • 2020-12-21 01:02

    You could use window.eval() to run eval() from global scope. This will assign var as a variable of window, which is what a global variable is: a variable attached to window.

    ... But you really really shouldn't. eval() is sandboxed for a reason.

    That is not unless you really know what you are doing and trust everything you are receiving through XMLHttpRequest. It is one of those chicken/egg things: if you trust the code enough to execute it, it should be programmed well enough to prefix global variables with window. to begin with; thus, you should not need to use window.eval().

    Besides, unless you are just trying to avoid async headaches by using the more-manageable XMLHttpRequest (there's a first time for everything...), you really should just create a script tag, assign it's source, and append it as a child to the head or body tag. Dynamically appending script tags is even faster than using XHR, especially for big scripts.

    0 讨论(0)
提交回复
热议问题