0

I have a project where I have three separate JavaScript files (example1.js, example2.js and example3.js lets call them) scripted into one html file (index.html). These three JS files between them are responsible for an API call and manipulating the result.

One of the JS files, example1.js refers to a global variable located in example2.js and as they were both loading into the same html document I thought the access to said variable wouldn't be an issue and it did indeed work perfectly fine until I added the files to my RoR app. Due to Rails I had to encase the JS/jQuery code inside of $document.ready(function(){} (I should probably should do this as a matter of course anyway?).

The effect this has had is that I am now getting a 'variable not defined' error on the global variable referred to by example1.js that is located in example2.js, even though other code in the same file is working correctly.

I went back to my original JS files away from RoR incase it was a Rails issue. However, encasing the code in my original files with the jQuery document.ready function has the same effect outside of the Rails environment. Can someone explain why this is and a possible solution?

  • Please provide code sample as per [mcve]. Sounds like your scope understanding is incorrect – charlietfl Feb 05 '17 at 16:53
  • 3
    When you wrap code in a function, as for a "ready" handler, the variables are *local* to that function and not *global*. – Pointy Feb 05 '17 at 16:53
  • @Pointy so you can explain this? http://jsbin.com/puyuyig .thanks – plonknimbuzz Feb 05 '17 at 17:28
  • @plonknimbuzz in that code, the function used for the "ready" handler declares no variables whatsoever; it's *using* global variables, which is fine. Note that you posted none of your actual code, so it's hard to say exactly what your problem is. – Pointy Feb 05 '17 at 17:31
  • @Pointy i upload my script to my VPS http://31.220.58.88/so/js_global/ hope you can explain that. thanks – plonknimbuzz Feb 05 '17 at 17:43
  • Your code should be posted **here**, on this site. – Pointy Feb 05 '17 at 17:46
  • Agreed with others, sounds like a problem with scope understanding. I recomend reading [You Don't Know JavaScript - scope](https://github.com/getify/You-Dont-Know-JS/tree/master/scope%20%26%20closures). It helped me understand scope and closures. – Karl Galvez Feb 05 '17 at 18:05
  • I didn't see this answer earlier but I think this explains http://stackoverflow.com/questions/4363113/jquery-scope-inside-document-ready it and now that I think about it it makes perfect sense that the document.ready function encloses the variables into its function scope and out of the global scope. – PaulWallis42 Feb 05 '17 at 18:06

1 Answers1

0

I completely overlooked the fact that document.ready is itself a function and therefore removed everything from the global scope into the function scope of document.ready.