简体   繁体   English

关于导入js模块和function作用域(local/global)的问题

[英]Question about importing js module and function scope(local/global)

Hi I'm new in js and I'm trying to understand local/global scope when importing js module.嗨,我是 js 新手,我正在尝试在导入 js 模块时了解本地/全局 scope。

Below is my html/js file which is working.下面是我正在工作的 html/js 文件。

enter image description here在此处输入图像描述

Below is my html/js file which is not working.下面是我的 html/js 文件,它不起作用。

在此处输入图像描述

Please tell me the reason why I have to put document.querySelector~~~ and why the second one doesn't work..请告诉我为什么我必须放 document.querySelector~~~ 以及为什么第二个不起作用..

Your main.js should be:你的 main.js 应该是:

import {make_black} from "/static/sub.js";

window.make_black = make_black;

When you import an external script as a module using script tags, the module code is run but exports are not accessible in anyway.当您使用脚本标签将外部脚本作为模块导入时,模块代码会运行,但无论如何都无法访问导出。 You have to explicitly add them to the window, like in the example above.您必须将它们显式添加到 window,如上例所示。 Then you will be able to access make_black inside your html onclick attribute.然后,您将能够访问 html onclick 属性中的 make_black。

If you wanted to export something from a module, for example:如果您想从模块中导出某些内容,例如:

main.js main.js

import {make_black} from "/static/sub.js";

export let mb = make_black;

and then access your mb function inside your main.html, you would have to do something like this:然后在 main.html 中访问您的 mb function,您必须执行以下操作:

main.html main.html

<script type="module">
    import {mb} from "/static/main.js";
    // now you can use mb here, which is a reference to your make_black function
    // inside sub.js
</script>

If you just import an external script as a module, there is no way to access its variables in its scope.如果只是将外部脚本作为模块导入,则无法访问其 scope 中的变量。 You have to either import them inside script tags with type="module" (as shown above) or explicitly make them available by assigning them to the window inside your js file (also as shown above).您必须将它们导入到带有 type="module" 的脚本标签中(如上所示),或者通过将它们分配给 js 文件中的 window 显式使它们可用(也如上所示)。 It's a little confusing the way that modules work in the browser!模块在浏览器中的工作方式有点令人困惑!

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

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