scope - Seemingly defined javascript variable throws undefined error -
given following code, i'm not sure why can retrieve longandobscurevariablename not anotherlongobscurevariablename. can explain, , show how make anotherlongobscurevariablename accessible jsfilenumbertwo.js?
head of html document contains:
<script type="text/javascript" id="my_globals"> var longandobscurevariablename = "foo"; </script> <script type="text/javascript" src="jsfilenumberone.js" /></script> <script type="text/javascript" src="jsfilenumbertwo.js" /></script>
javascript file jsfilenumberone.js contains code, adds global variable #my_globals element:
jquery(document).ready(function() { // store initial variables, add more var initialvars = jquery('#my_globals').html(); // define content script tag: var scriptcontent = initialvars; // add script content scriptcontent += 'var anotherlongobscurevariablename = "bar";\n'; function insertnewinfo() { jquery('#my_globals').html(scriptcontent); }; insertnewinfo(); });
when jsnumberone.js executes, #my_globals changes this:
<script type="text/javascript" id="my_globals"> var longandobscurevariablename = "foo"; var anotherlongandobscurevariablename = "bar"; </script>
javascript file jsfilenumbertwo.js contains code, trying find out value of anotherlongandobscurevariablename:
jquery(document).ready(function($) { console.log('longandobscurevariablename'); // log displays "foo" console.log('anotherlongandobscurevariablename'); // log displays "uncaught referenceerror: anotherlongandobscurevariablename not defined" console.log('window.anotherlongandobscurevariablename'); // log displays "undefined" settimeout(function(){ console.log(window.anotherlongandobscurevariablename); },2000); // log still displays "undefined" });
i can't retrieve anotherlongandobscurevariablename within jsfilenumbertwo.js, though thought adding global scope putting head of html document.
is scope issue? timing/sequencing issue? think jsfilenumbertwo.js may accessing head content before jsfilenumberone.js executes, settimeout function added still "undefined".
what going on? how can make work?
the scripts running top bottom. second script modifies first, has run , not run again, has no effect.
additionally, should put things on window make globals.
so replace
scriptcontent += 'var anotherlongobscurevariablename = "bar";\n'; function insertnewinfo() { jquery('#my_globals').html(scriptcontent); }; insertnewinfo();
with
window.anotherlongandobscurevariablename = "bar";
,
var longandobscurevariablename = "foo";
with
window.longandobscurevariablename = "foo";
Comments
Post a Comment