Javascript经典脚本与模块范围



我的javascript前端代码中有一些奇怪的行为,所以我要问一个回归基础的问题。首先,我将设置一些示例。

script1.js

var script1Var = "script variable";
function script1Test(){
console.log("hello from script1 test");
}

script2.js

function script2Test(){
console.log("hello from script2 test");
}

模块1.js

export default function module1Test(){
console.log("hello from module1 test");
}

模块2.js

export default function module2Test(){
console.log("hello from module2 test");
}

test_page1.html

<html>
<head>
<script src="script1.js"></script>
<script src="script2.js"></script>
</head>
</html>

test_page2.html

<html>
<head>
<script type="module" src="module1.js"></script>
<script type="module" src="module2.js"></script>
<script src="script1.js"></script>
<script src="script2.js"></script>
</head>
</html>

以下是我的问题:

  1. 在运行时,由于test_page1.html的布局,我认为script2.js可以在不需要任何导入的情况下调用script1.js中的函数,但script1.js可以调用script2.js中的函数吗?基本上秩序重要吗?我很肯定它确实如此
  2. test_page2.html中,module1.jsmodule2.js的函数对script1.jsscript2.js可见吗?如果没有,如何让他们看到它们
  3. test_page2.html中,module1.js中的函数对module2.js是否可见,而不使用导入

基本上,我的问题可以归结为,如何在模块中使用经典脚本(其中没有导出(?以及如何在经典脚本中使用模块。将经典脚本转换为模块不是一个选项,因为有很多代码依赖于将其用作经典脚本。模块也是如此,它们无法转换为经典脚本,因为有其他代码将它们用作模块。

谢谢你的帮助

  1. 〔…〕但是script1.js可以调用script2.js中的函数吗?基本上秩序重要吗?我很肯定它确实如此

这取决于情况。script1.js在对script2.js进行求值时无法从其调用函数。即类似的东西

// script1.js
script2Test();

不起作用。

但只要在加载script2.js之后,它就可以调用这些函数。例如响应事件:

// script1.js
document.body.onclick = function() {
script2Test();
}
  1. 在test_page2.html中,module1.js和module2.js中的函数对script1.js和script2.js可见吗

否。每个模块创建一个单独的作用域。只能通过导入来访问导出。

如果没有,如何使它们对他们可见?

模块必须显式创建全局变量,例如通过将属性分配给window:

window.module1Test = module1Test;

但在这里,这样的函数只有在加载/评估模块之后才能调用。

更好的解决方案(至少我相信这在"正常"脚本中有效(是通过import函数动态导入模块:

import('./module1Test.js').then(exports => console.log(exports));
  1. 在test_page2.html中,module1.js中的函数在不使用导入的情况下对module2.js可见吗

否。正如我所说,每个模块都创建自己的范围。

最新更新