[英]How To Make a Javascript Variable Only Accessible From One Script Tag?
我想知道是否可以使變量只能從 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>
有什么辦法可以讓這個工作,讓其他腳本標簽不能訪問第一個的變量?
使用const
或let
來分配變量。
將變量包裝在一個塊中,即{}
。
<script> { const abc = "this is a variable"; } </script> <script> alert(abc); </script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.