简体   繁体   中英

Can Modules access variables stored in other modules that have not been imported, but both modules are exported to a main file?

I am a beginner in the world of JavaScript, and I am just learning about modules and how to use them.
Here is the situation:
I have a main.js file and two module#.js files, module1.js and module2.js .

project/
    main.js
    modules/
        module1.js
        module2.js

These files have both been individually imported into main.js , but module2.js contains a function displayAll() that is meant to display all the items in an array items = [item1, item2, item3] .

function displayAll() {
  for (let i = 0; i < items.length; i++) {
  console.log(`Item ${i} is ${items[i]}`)
  }
}

This is not exactly how it looks, but that is beside the point. My question is since the above function is contained in module2.js , how do let it access the array items that is contained in module1.js ? What if another file needed it? How could I export it to multiple files without creating a messy web of imports?
I am not familiar with any frameworks yet, so please only use core javascript as much as possible.
Thanks!

First you need to create a function that loads what you need.

In module2.js, you create this function that appends the module1.js to it

function loadJS(callback) {                
    var firstScriptElem = document.getElementsByTagName('script')[0], script = document.createElement('script');

    script.type = 'text/javascript';
    script.src = module1.js; 
    script.async = false; 

    // Binds the event to the callback function. We use more than one event for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;

    firstScriptElem.appendChild(script);       

};

You then need to create a callback function that actually runs the code you want to run after retrieving module1.js

function callBack() {
// get your array

// do something with the array

}

Now in module2 you call loadJS(callBack) and there you have it.

Now I know you are new and don't want to dive into frameworks yet. But I should mention to you that requireJS does all of this very simply. I was using the kind of code above for a while but once I started using requireJS, I realize I should have used it from the beginning because its way more organized and you definitely don't have to repeat yourself with it. Makes module management easier (I too, only recently started learning the module patterns in javascript).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM