I noticed everywhere that people mention “ Just define a variable at the top of your JS code and it will become global ” in response to questions such as “ How do I create a global variable from within a function? ”. Most of the answers begin with the fact that it is impossible to achieve this. Of course, this can be done:
<script type="text/javascript">
window.spam = 'Hello World';
</script>
Then, in your code, you can say:
<script type="text/javascript">
alert(spam);
</script>
This works great in IE6 +, Firefox, Chrome, Safari, etc. So why does no one do this?
In my case, I want people to access a global variable with a name fooBarfrom anywhere in their code and in my AJAX library, I want the variable to automatically update behind the scenes, so when they say $.do_some_magic()they can fooBarreflect what changes made $.do_some_magic()without thinking about it. I don’t want them to have to create an up variable in their code, nor do I want to create an up variable in my library code. I suppose I just hate defining global variables at the top and would prefer if there is no good reason not to. There is?
source
share