我在哪里声明网页中的全局 JavaScript 变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4247927/
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
Where do I declare global JavaScript variables in a web page?
提问by Tony the Pony
Where do I need to place a snippet of JavaScript code that initializes a variable that must be visible to all code executed with the page? (For example, event handlers on elements will need to access this variable).
我需要在哪里放置一段 JavaScript 代码来初始化一个变量,该变量必须对所有与页面一起执行的代码可见?(例如,元素上的事件处理程序将需要访问此变量)。
回答by meder omuraliev
The onlyway to not have a global variable is to use the var
keyword in the scope of a function. Anything else is a global variable.
没有全局变量的唯一方法是var
在函数范围内使用关键字。其他任何东西都是全局变量。
(function() {
var local = 5;
})();
It doesn't matter if the function is a literal or function definition, it hasto be some type of function.
函数是文字还是函数定义并不重要,它必须是某种类型的函数。
Global variable examples:
全局变量示例:
1:
1:
var global = 5;
The above is not in a function scope, therefore global even if var
is used.
以上不在函数范围内,因此即使var
使用global 。
2.
2.
(function() {
global = 5;
})();
In the above, no var
was used, so it becomes an implied global.
在上面, novar
被使用了,所以它变成了一个隐含的全局变量。
3.
3.
function foo(){}
foo
was not defined inside of another function or assigned to a object key so its globally accessible.
foo
未在另一个函数内部定义或分配给对象键,因此可全局访问。
4.
4.
(function() {
var local = global = 5;
})();
When doing multiple assignments with var
, only the first variable becomes local... so global
is a global variable and equates to 5.
使用 进行多次赋值时var
,只有第一个变量成为局部变量……global
全局变量也是如此,等于 5。
5.
5.
window.foo = 5;
Prefixing window.
is an explicit way of defining a global variable in the context of a browser.
前缀window.
是一种在浏览器上下文中定义全局变量的显式方法。
6.
6.
this.x = 5;
By default in browsers, this
points to the DOMWindow unless you're in a method that's attached to an object which is not window
. It's the same as #5. Note that if you use a method like XMLHttpRequest, the context is of the window.
默认情况下,在浏览器中,this
指向 DOMWindow 除非您使用的方法附加到不是window
. 这与#5 相同。请注意,如果您使用 XMLHttpRequest 之类的方法,则上下文是窗口的。
7.
7.
with ( window ) { name = 'john'; }
If you use the with
statement and you dont reference an object that already has a property, a global variable is defined. It's best to avoid using the with
keyword in general.
如果使用该with
语句并且不引用已经具有属性的对象,则定义了一个全局变量。with
一般最好避免使用关键字。
Conclusion:
结论:
Personally, I would keep my code in an anonymous function scope, and onlyexplicitly declare globals when I need to.
就个人而言,我会将我的代码保存在匿名函数范围内,并且仅在需要时显式声明全局变量。
(function() {
var governor = 'Schwarzenegger',
state = 'California';
window.president = 'Obama';
})();
In the above, I define governor
and state
variables and they are local to my function. I want to explicitly define president
as a global variable. This way, I'm not confused about which variables I defined as globals or not, because I explicitly prefix them with window.
.
在上面,我定义了governor
和state
变量,它们对我的函数来说是本地的。我想明确定义president
为全局变量。这样,我就不会对我将哪些变量定义为全局变量感到困惑,因为我明确地在它们前面加上了window.
.
回答by SuperDuck
You can do it out of any function, or in a function without using the 'var' keyword. Assign it before any other scripts (very top of the page, likely) so the scripts can read the value.
您可以在任何函数中执行此操作,也可以在不使用“var”关键字的情况下在函数中执行此操作。在任何其他脚本(很可能是页面顶部)之前分配它,以便脚本可以读取该值。
You can also place it in an included JS file, but putting it right on the page is usually more usable as you can see the global values easily, and they can be modified for each page by the server-side code. Also try to prevent assigning global variables in the body, it may make confussions and will be harder to read.
你也可以把它放在一个包含的 JS 文件中,但是把它放在页面上通常更有用,因为你可以很容易地看到全局值,并且可以通过服务器端代码为每个页面修改它们。还要尽量避免在正文中分配全局变量,这可能会造成混乱并且更难阅读。
<head>
<script>
var numberOfDucks = 1000; // Global
function some_function() {
// numberOfDucks is accessible here
alert (numberOfDucks);
// until you mask it by defining a local variable using the 'var' keyword
var myLocal = 0; // is a local
anotherGlobal = 0; // is a global
}
</script>
<script>
// potentially some other script
</script>
<script src="even_more_script.js">
</head>
Defining a global in a function (implied-global) is not a good idea because it will make a lot of confussion.
在函数中定义全局(隐含全局)不是一个好主意,因为它会引起很多混乱。
回答by Tony the Pony
you could place that variable at the beginning of the page (in the global scope if you HAD to make it visible everywhere) but I suggest two things
您可以将该变量放在页面的开头(如果您必须让它在任何地方都可见,则在全局范围内)但我建议两件事
1) since you have to open a script block, avoid to declare it inside the body of your page since scripts block rendering. So put it just before </head>
1) 因为你必须打开一个脚本块,避免在你的页面主体中声明它,因为脚本块渲染。所以放在前面</head>
2) avoid to create a simple var but use a namespace instead so you reduce risks of identifier collision
2) 避免创建简单的 var 而是使用命名空间,这样可以降低标识符冲突的风险
<script>
var YOUR_APP_NS = {};
YOUR_APP_NS.yourvar = ....
</script>
this is a good practice in order to not polluting the global scope. If you need several public var in this way you could just write
为了不污染全局范围,这是一个很好的做法。如果你以这种方式需要几个公共变量,你可以写
YOUR_APP_NS.yourvar1 = ....
YOUR_APP_NS.yourvar2 = ....
YOUR_APP_NS.yourvarN = ....
but the global var is still 1
但全局变量仍然是 1
回答by Brian Scott
Declare the variable outwith of any of your functions, that way it becomes a global variable.
在任何函数之外声明变量,这样它就成为全局变量。
Here's an example of a global variable. The first function uses the global but the second function uses a local variable with the same name which masks the global.
下面是一个全局变量的例子。第一个函数使用全局变量,但第二个函数使用具有相同名称的局部变量来屏蔽全局变量。
var globalVar = 1;
function testFunc1 () {
globalVar = 2; //Updates the global variable
}
function testFunc2 () {
var globalVar = 5; // This variable masks the global and only updates within the scope of this function
globalVar = 3;
}
Also, you mentioned that the snippet must initialise the global before any other reference. For this I would suggest you place your script block or reference to your javascript file before any other javascript references in your element as possible. If you have other javascript files which are going to rely on the global variable then you may wish to ensure they do not load until the rest of the page has loaded first using the defer attribute. See the following:
此外,您提到该代码段必须在任何其他引用之前初始化全局。为此,我建议您尽可能将脚本块或对 javascript 文件的引用放在元素中的任何其他 javascript 引用之前。如果您有其他 javascript 文件将依赖于全局变量,那么您可能希望确保在使用 defer 属性首先加载页面的其余部分之前它们不会加载。请参阅以下内容:
<script src="dependant.js" type="text/javascript" defer="defer"></script>
Another option is to dynamically add your dependant scripts after your initial script has loaded. You can do this using something like jQuery as follows:
另一种选择是在您的初始脚本加载后动态添加您的依赖脚本。你可以使用类似 jQuery 的东西来做到这一点,如下所示:
$(window).load( function() {
$.getScript('dependant.js');
});
回答by Floyd
<head>
<script>
var b = 0;
</script>
<script src="...">
</head>
<body>
...
</body>