Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Patrick McKinney
13,151 PointsAccess to variables in other script files?
It seemed that at at one point in the video he said using these techniques provides a way to access a variable from another script file in the script file you are working with.
Am I correct in that understanding?
For example,
Let's say in the main.js file, there is a variable called map. And map has a loaded option (map.loaded). You could use the techniques he showed to gain access to map and map.loaded in a separate script file called customize.js?
2 Answers
Jeremy Castanza
12,081 PointsYou're referring to a concept in programming called "variable scope." Here's a really good article on Javascript variable scope that should answer your question in simple terms. http://www.w3schools.com/js/js_scope.asp
Steven Parker
243,656 PointsGlobal variables should be accessible from anywhere in the program, no matter what file they are defined in.
Another way of sharing variables (and methods) is via "dependency injection". This is where an object containing resources (variables and/or methods) is passed as a parameter to a function, which then has access to them.
Leonard Theisen
16,518 PointsLeonard Theisen
16,518 PointsFrom my understanding once you've 'loaded' the .js file(s) they can all be accessed. The functions and global variables in each file is treated as if it's in the main page.
whether the javascript is in the .html file or a .js file, or multiple .js file it all works the same once the page as been loaded or accessed.