是否可以更改具有初始相同范围的变量的范围?

is it possible to change the scope of variables with initially equal scopes?

我想知道我是否可以使变量的范围超出模块脚本标签,或者我是否可以以某种方式导出它并导入另一个脚本标签。

我目前的代码是这样的:

<script>
    var variable1 = 'first variable :)';
    var variable2 = 'second variable :)';
</script>
<script>
    // i want to be able to access variable1 here, but not variable2
</script>

这样的事情可能吗?

我已经尝试了 varletconstwindow.,但它们没有区别。 我还尝试将第一个脚本作为模块,但后来我无法访问 variable1,并且(我认为)无法使用 import/export.

备注: 如果没有其他选择,我只想将脚本分成单独的文件。

由于 variable1variable2 是在同一范围内定义的(在顶层),因此无法在别处只访问一个而不能访问另一个 - 除非您更改了第一个脚本标记类似于

<script>
    var variable1 = 'first variable :)';
    (() => {
        var variable2 = 'second variable :)';
        // do stuff with variable2
    })();
    // variable2 cannot be seen outside
</script>

i only want to separate the scripts into separate files if there is no other option

这是一个非常好的选项,如果您正在做一些相当专业的事情并且要编写的代码不是微不足道的,您应该考虑。我强烈推荐它,它使编写和维护代码的过程变得非常非常容易。是的,确实需要一些时间来弄清楚并习惯,但这是值得的,IMO。

您还可以使用模块脚本并使用 window 对象存储变量:

<script type="module">
  var variable1 = 'first variable :)';
  // not accessible by others scripts
  
  window.variable2 = 'second variable :)';
  // accessible by others scripts
</script>

<script>
  console.log(window.variable2)
  setTimeout(() => console.log(variable2), 10)
</script>