[英]How to declare global variables using JS
如何使用 JavaScript 聲明一個全局變量,它的生命在 HTML 代碼中仍然存在? 我們可以在另一個腳本中訪問我們在一個腳本中聲明的變量嗎?
“不要這樣做”是一個簡單的答案。 堵塞全局 scope 通常是一件壞事,特別是如果您必須問如何(這通常意味着您之所以問是因為您認為這是簡單的解決方案,但它幾乎肯定不是正確的解決方案)。 你到底想做什么?
如果你真的想,要么:
var
關鍵字window.variable = value
在任何 function 之外聲明一個變量。 它將可以在其他腳本中訪問。
Global variables are declared by using either the var
keyword outside of the scope of a function, by assigning a variable without using var, or by directly assigning a property of the window
object.
<script>
var global1 = 'foo';
global2 = 'bar';
window.global3 = 'baz';
function f() {
var not_global;
}
</script>
在其他腳本之前在腳本標簽中聲明一個變量。
<script type="text/javascript">
var global = "hello world";
</script>
在<script>
標簽中聲明你的變量,但確保將它放在<body>
標簽中,否則瀏覽器可能不會執行它!
或者,您可以使用 cookie。
在 function 或 class 之外定義的任何變量都是 Javascript 中的全局變量。
例如:
<script>
var itsAGlobalVariable;
function someMethod() {
var itsALocalVariable;
}
</script>
你的意思是這樣的:
var Foo = {
Bar: Value
}
然后你可以這樣訪問:
Foo.Bar
您還可以設置值:
Foo.Bar = "fancy value"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.