Using eval () to set global variables

My code for setting a global variable using eval does not work. It is as if the assignment is not being called at all, but script errors are not occurring.

 <script type="text/javascript"> $(function() { setTimeout(function() { eval('var x = 1;'); alert(x); }, 0); }); </script> <div onclick="alert(x);">Click to see 'x'</div> 

When the page loads, a warning shows what I expect; it confirms that x = 1. But after that I click on the div and get a javascript error that x is undefined. How do I make eval add this variable correctly?

Background: The above code is an example of minimal playback from a project I'm working on, where we have to execute javascript code during AJAX responses. eval works normally most of the time, but it causes problems.

+4
source share
3 answers

Eval runs locally, you set a local variable.

To set a global variable, remove var ;

 <script type="text/javascript"> $(function() { setTimeout(function() { eval('x = 1;'); alert(x); }, 0); }); </script> 
+3
source

You can use window.eval() to run eval() from the global scope. This will assign var as the window variable, which is a global variable: the variable bound to window .

... But you really shouldn't do that. eval() is the default sandbox.

This is not the case if you really don’t know what you are doing and trust everything you get through XMLHttpRequest . This is one of these things from chicken / eggs: if you trust enough code to execute it, it must be programmed well enough to start with the global variable prefix using window. ; this way you do not need to use window.eval() .

Also, if you're just not trying to avoid asynchronous headaches by using the more manageable XMLHttpRequest (there for the first time for everything ...), you really just need to create a script tag, assign it a source, and add it as a child to the head tag or body. Dynamically adding script tags is faster than using XHR, especially for large scripts.

+5
source

I would not recommend setting global variables, but if you absolutely need to, use the window object:

 window['x'] = 1; 
+2
source

All Articles