Issue
I was following a React tutorial where a javascript file A containing some functions and various console log statements etc is imported into another javascript file B.
One of those functions from file A is then called in file B but there was an error, yet all the console log statements and other commands from file A executed fine.
I wondered why some parts of the file A ran ok but not the functions, doesn't importing the whole file essentially bring everything in that file into scope for file B?
For instance:
a.js
console.log("hi");
function test1() {
console.log("test1");
}
b.js
import './a.js';
test1();
Solution
...doesn't importing the whole file essentially bring everything in that file into scope for file B?
No, not at all. The example module you've shown doesn't export anything, so everything inside it (the test1
function) is entirely private to the module. This is one of the key benefits of modules: They provide private scope for module details that you don't want to share, with an explicit way to share the things you do want to share.
I wondered why some parts of the file A ran ok but not the functions...
That's because you've imported the module. Even if the module doesn't import or export anything, its top-level code is still run as part of the process of loading it (the first time it's imported). Some modules are designed purely to be loaded for their side-effects (what their top-level code does). Your example is like that; its side effect is the console.log
it does.
Answered By - T.J. Crowder Answer Checked By - Mildred Charles (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.