[英]Can Modules access variables stored in other modules that have not been imported, but both modules are exported to a main file?
我是JavaScript領域的初學者,我只是在學習有關模塊以及如何使用它們的知識。
情況如下:
我有一個main.js
文件和兩個module#.js文件, module1.js
和module2.js
。
project/
main.js
modules/
module1.js
module2.js
這些文件都已分別導入到main.js
,但是module2.js
包含一個函數displayAll()
,用於顯示數組中的所有項目items = [item1, item2, item3]
。
function displayAll() {
for (let i = 0; i < items.length; i++) {
console.log(`Item ${i} is ${items[i]}`)
}
}
這並不完全是它的外觀,但這是重點。 我的問題是, 由於上述函數包含在module2.js
,如何讓它訪問module1.js
包含的數組items
? 如果需要另一個文件怎么辦? 我如何將其導出到多個文件而不創建混亂的導入網絡?
我還不熟悉任何框架,因此請盡可能多地使用核心javascript。
謝謝!
首先,您需要創建一個加載所需內容的函數。
在module2.js中,創建此函數,將module1.js附加到該函數
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);
};
然后,您需要創建一個回調函數,該函數實際上將在檢索module1.js后運行您要運行的代碼
function callBack() {
// get your array
// do something with the array
}
現在在module2中,調用loadJS(callBack)
並在其中找到它。
現在,我知道您是新手,還不想深入研究框架。 但是我要向您提及,requireJS非常簡單地完成了所有這些工作。 我已經使用了一段時間,但是一旦我開始使用requireJS,我意識到我應該從一開始就使用它,因為它的組織方式更加合理,您當然不必重復它。 使模塊管理更加容易(我也是,最近才開始學習javascript中的模塊模式)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.