I am by no means a guru with JavaScript, so my apologies if this questions sounds "beginner". But why is it that if I have 3 JavaScript files in a project, that any of those 3 JavaScript files can call any of the other functions that are in the other JavaScript files?
The bigger question is how can this be stopped? an example would be if, of these 3 hypothetical JavaScript files, just say they are named as ManagerJS.js, TeamAJS.js and TeamBJS.js, I don't want TeamAJS to be able to access TeamBJS but I want them both to be able to access ManagerJS.
Asked
Active
Viewed 62 times
1

Chris
- 2,953
- 10
- 48
- 118
-
3There is a singe shared global scope per page. You can prevent access by not defining stuff in global scope. You can use an IIFE to create a private scope for each script. Search for "revealing module pattern". – Felix Kling Jun 11 '16 at 01:17
-
IIFE: https://en.wikipedia.org/wiki/Immediately-invoked_function_expression – ceejayoz Jun 11 '16 at 01:18
-
Duplicate. See http://stackoverflow.com/a/111111/6326441 – Bryan Euton Jun 11 '16 at 01:20
-
@FelixKling, so to make sure I understand what you are saying...If I have two scripts being referenced in an html page, those 2 scripts will be able to access each other? – Chris Jun 11 '16 at 01:24
-
1Depends on what the scripts contain. Both are evaluated in the same scope. – Felix Kling Jun 11 '16 at 01:28
2 Answers
2
All scripts on a page are evaluated in global scope. There is a single shared global scope per page.
You can prevent access by not defining stuff in global scope. You can use an IIFE to create a private scope for each script:
// myScript.js
(function() {
// everything declared here is *local* to this function
var localValue = 42;
// we could expose values by explicitly creating global variables
// (but there are other, more elaborate ways)
window.globalValue = 21;
}());
Only expose values that you want other code / scripts to access. There are various ways to do that, one of them is the revealing module pattern.
See also What is the purpose of a self executing function in javascript?

Community
- 1
- 1

Felix Kling
- 795,719
- 175
- 1,089
- 1,143
1
It sounds like you want to use some kind of dependency injection system. There are quite a few options out there, including CommonJS, RequireJS, ES6 imports, and probably a lot of others.
Here's an example in CommonJS
// in TeamAJS.js...
// gain reference to Manager script
var Manager = require('./ManagerJS')
// do things with Manager
// note: can't access TeamBJS unless you require it as a dependency
module.exports = {
// put methods or variables in here that you wish to expose to other modules
}
The RequireJS site has a nice article on modules

posit labs
- 8,951
- 4
- 36
- 66
-
I was kinda hoping it would work like in a C# project where you have to reference a class in a controller, or the code behind page. IE using MyProject.Models – Chris Jun 11 '16 at 02:34
-
-