如何在 javascript 和 HTML 中声明全局变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3454105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to declare global var in javascript and HTML?
提问by Richard
How to declare a variable, I think global, the way I declare in an html file and then use it in a js file (included by <script>tags)?
如何声明一个变量,我认为是全局的,就像我在 html 文件中声明然后在 js 文件中使用它(包含在<script>标签中)一样?
回答by Quentin
Don't use the varkeyword
不要使用var关键字
(That said, globals are usually the wrong solution to any given problem in JS)
(也就是说,全局变量通常是 JS 中任何给定问题的错误解决方案)
回答by Jacob
You can assign to the windowobject, i.e. window.myGlobal = 3;. windowis the default context for variable binding. That's why you can reference documentinstead of needing to do a window.document.
您可以分配给window对象,即window.myGlobal = 3;. window是变量绑定的默认上下文。这就是为什么您可以引用document而不需要执行window.document.
But yeah as David says, you should avoid using globals. And if you are going to use globals, you should place them and other top-level declarations in a "namespace" object to avoid potential naming collisions with other libraries, like this:
但是正如大卫所说,你应该避免使用全局变量。如果你打算使用全局变量,你应该将它们和其他顶级声明放在一个“命名空间”对象中,以避免与其他库的潜在命名冲突,如下所示:
myNamespace = { myGlobal: 3 };
// Then to access...
myNamespace.myGlobal = 6;
回答by Jacob
So as I understand, you want to use a variable from an HTML file in a JS file? To pass a variable from an HTML file to a javascript file, pass it with a function:
据我了解,您想在 JS 文件中使用 HTML 文件中的变量吗?要将变量从 HTML 文件传递到 javascript 文件,请使用函数传递它:
HTML.html
HTML.html
<a href="#" onClick="test('John Doe')">Send Name</a>
Javascript.js
Javascript.js
function test(full_name) {
alert(full_name);
}
回答by Buddy
Please, avoid using global variables.
请避免使用全局变量。
To answer your question, there are two ways of declaring a global variable in JavaScript. You can either omit the 'var' keyword, or declare the variable outside any function.
为了回答您的问题,在 JavaScript 中有两种声明全局变量的方法。您可以省略“var”关键字,也可以在任何函数之外声明变量。
In this code sample, both thisIsGlobal and thisIsAlsoGlobal are global variables and set to null.
在此代码示例中, thisIsGlobal 和 thisIsAlsoGlobal 都是全局变量并设置为 null。
var thisIsGlobal= null;
function foo() {
thisIsAlsoGlobal = null;
// code goes here
}

