簡體   English   中英

從另一個文件調用時出現Javascript范圍錯誤

[英]Javascript scope error when calling from another file

我在這里做錯了什么? 我在FILE1中定義了一個變量,然后在FILE2中需要了FILE1,並且在MAIN中需要了FILE2,因此我希望能夠從MAIN和FILE2中訪問全局my_global ,但是會引發錯誤。

文件1

var my_global=42;

文件2

require('FILE1');
var harvesterCount=12;
console.log(harvesterCount+my_global); //throws error
module.exports = function () {...}

主要

require('FILE2');
console.log(my_global); //error here

錯誤聲明(來自Screeps控制台):

ReferenceError: my_global is not defined
    at module.exports:8:5
    at Object.module.exports.loop:6:5
    at __mainLoop:1:12057
    at eval:2:4
    at Object.c.runCode:6:26869

嘗試使用<script>標記而不是require來引用文件

我在stackoverflow的另一個答案中看到了require 希望這可以幫到你。

require()不是標准JavaScript的一部分。 針對您的問題和標簽,Node.js中內置了require()來加載模塊。 這個概念類似於C / Java / Python / [在此處插入更多語言]導入或包含。

模塊的概念類似於僅通過標簽添加少量JavaScript代碼。 與添加標簽不同,它不會將文件泄漏到全局范圍內

行為是正確的,您應該導出變量。 例如

var my_global=42;
exports = {
  my_global:my_global
}

您可以使用以下引用導出的變量

var m = require('file1');
console.log(m.my_global);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM