Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使Javascript变量只能从一个脚本标记访问?_Javascript_Html_Variables - Fatal编程技术网

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

如何使Javascript变量只能从一个脚本标记访问?,javascript,html,variables,Javascript,Html,Variables,我想知道是否可以只从HTML网页中定义的脚本标记访问变量。例如,如果我在脚本标记中声明了一个变量,页面中的其他脚本标记将无法访问它。以下是一个例子: <html> <body> <script> //This is script 1 var abc = "this is a variable" // How can I make this variable only accessible by this

我想知道是否可以只从HTML网页中定义的脚本标记访问变量。例如,如果我在脚本标记中声明了一个变量,页面中的其他脚本标记将无法访问它。以下是一个例子:

<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>

//这是脚本1
var abc=“这是一个变量”//如何使此变量只能通过此脚本访问?
警报(abc)//这应该会出现“abc未定义”错误,因为它只能在其他脚本标记中访问。
是否有任何方法可以使此工作正常,从而使其他脚本标记无法访问第一个脚本标记的变量

  • 使用
    const
    let
    分配变量

  • 将变量包装在块中,即
    {}

  • 
    {
    const abc=“这是一个变量”;
    }
    警报(abc);
    
  • 使用
    const
    let
    分配变量

  • 将变量包装在块中,即
    {}

  • 
    {
    const abc=“这是一个变量”;
    }
    警报(abc);
    
    您能详细说明您在这里试图解决的实际问题吗?您是否担心页面中包含的脚本会读取您在单独的
    块中声明的变量的内容?能否详细说明您在这里试图解决的实际问题?您是否担心页面中包含的脚本会读取您在单独的
    块中声明的变量的内容?