简体   繁体   English

Javascript 从模块内部访问全局变量

[英]Javascript access global variable from inside the module

I am trying to access a global variable or a function from inside the module, but it still writes error that testFunction is not defined.我正在尝试从模块内部访问全局变量或 function,但它仍然会写入未定义 testFunction 的错误。

index.html:
<script src="main.js" type="module">

main.js:
import { runTestFunction } from './js/TestModule.js';
function testFunction() {
 alert('hello');
 }
runTestFunction();

TestModule.js:
export function runTestFunction() {
testFunction();
}

You declare testFunction() in main.js but you are trying to call it in TestModule.js您在 main.js 中声明testFunction()但您试图在 TestModule.js 中调用它

You have a few choices:你有几个选择:

  1. Declare testFucntion() in TestModule.js在 TestModule.js 中声明testFucntion()
  2. Implement the body of testFunction() in runTestFunction()runTestFunction()中实现testFunction()的主体
  3. If you need to declare a function in main.js and then call it in TestModule.js then pass it to runTestFunction() as a parameter like:如果您需要在 main.js 中声明一个 function 然后在 TestModule.js 中调用它,然后将其作为参数传递给runTestFunction() ,如下所示:

:

TestModule.js:
export function runTestFunction(testFunction) {
    testFunction();
}

main.js:
import { runTestFunction } from './js/TestModule.js';
const testFunction=()=>{
     alert('hello');
 }
runTestFunction(testFunction);

EDIT: To follow up on your comment about scope chain.编辑:跟进您对 scope 链的评论。

The reason why it is "not declared" because you have the import before the declaration.之所以“未声明”是因为您在声明之前有导入。 The code is executed from top to bottom.代码从上到下执行。 This means the function is declared after you tried to reference it.这意味着 function 在您尝试引用它之后被声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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