gpt4 book ai didi

javascript - 模块和脚本有什么区别?

转载 作者:行者123 更新时间:2023-12-02 23:54:02 25 4
gpt4 key购买 nike

我正在尝试通过 Typescript 文档来理解与 ES6 模块相同的模块。

typescript-modules - Typescript 模块的文档。它说的是

Modules are executed within their own scope, not in the global scope; this means that variables, functions, classes, etc. declared in a module are not visible outside the module unless they are explicitly exported using one of the export forms. Conversely, to consume a variable, function, class, interface, etc. exported from a different module, it has to be imported using one of the import forms.

还有

In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module. Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well).

它表示文件中没有导入或导出语句的任何内容都可以全局使用。但事实并非如此。

  • 文件夹
    • script1.js
    • script2.js

script1.js

var 变量 = "Hello";

script2.js

console.log(变量);

根据文档中编写的语句,当我运行 script2.js 时,它不应该给出任何错误并控制台变量的值,因为 script1.js 没有 import、export 语句,因此变量在全局中可用范围。但它给出了一个错误。那么脚本内容在全局范围内可用是什么意思?

最佳答案

在 HTML 文件中,如果执行 <script src="./script2.js" /><script src="./script1.js" /> ,你会看到Hello在控制台中。

关于javascript - 模块和脚本有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55488642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com