简体   繁体   English

如何使 Javascript 变量只能从一个脚本标记访问?

[英]How To Make a Javascript Variable Only Accessible From One Script Tag?

I was wondering if it was possible to make a variable only accessible from the script tag that it is defined in in an HTML webpage.我想知道是否可以使变量只能从 HTML 网页中定义的脚本标签访问。 For example, if I declare a variable in a script tag, the other script tags in the page can't access it.例如,如果我在脚本标签中声明了一个变量,页面中的其他脚本标签就无法访问它。 Here is an example:这是一个例子:

<html>
  <body>
    <script>
      //This is script 1
      var abc = "this is a variable" // How can I make this variable only accessible by this script?
    </script>
    <script>
      alert(abc) // This should give 'abc is not defined' error because it is only accessible in the other script tag.
    </script>
  </body>
</html>

Is there any way to make this work, so that the other script tags can not access the variables of the first one?有什么办法可以让这个工作,让其他脚本标签不能访问第一个的变量?

  1. Use either const or let to assign variables.使用constlet来分配变量。

  2. Wrap the variable in a block, ie {} .将变量包装在一个块中,即{}

 <script> { const abc = "this is a variable"; } </script> <script> alert(abc); </script>

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

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