如何在 JavaScript 中声明全局变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3352020/
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 a global variable in JavaScript?
提问by Dancer
How can I declare a global variable in JavaScript?
如何在 JavaScript 中声明全局变量?
回答by Felix Kling
If you have to generate global variables in production code (which should be avoided) alwaysdeclare them explicitly:
如果您必须在生产代码中生成全局变量(应该避免),请始终明确声明它们:
window.globalVar = "This is global!";
While it is possible to define a global variable by just omitting var(assuming there is no local variable of the same name), doing so generates an implicitglobal, which is a bad thing to do and would generate an error in strict mode.
虽然可以通过省略var(假设没有同名的局部变量)来定义全局变量,但这样做会生成一个隐式全局变量,这是一件坏事,并且会在严格模式下产生错误。
回答by Tomas Aschan
If this is the only application where you're going to use this variable, Felix's approach is excellent. However, if you're writing a jQuery plugin, consider "namespacing" (details on the quotes later...) variables and functions needed under the jQuery object. For example, I'm currently working on a jQuery popup menu that I've called miniMenu. Thus, I've defined a "namespace" miniMenuunder jQuery, and I place everything there.
如果这是您要使用此变量的唯一应用程序,那么 Felix 的方法非常好。但是,如果您正在编写 jQuery 插件,请考虑 jQuery 对象下所需的“命名空间”(后面的引号中的详细信息...)变量和函数。例如,我目前正在开发一个名为 miniMenu 的 jQuery 弹出菜单。因此,我miniMenu在 jQuery 下定义了一个“命名空间” ,并将所有内容都放在那里。
The reason I use quotes when I talk about javascript namespaces is that they aren't really namespaces in the normal sense. Instead, I just use a javascript object and place all my functions and variables as properties of this object.
我在谈论 javascript 命名空间时使用引号的原因是它们并不是通常意义上的真正命名空间。相反,我只是使用一个 javascript 对象并将我的所有函数和变量作为该对象的属性。
Also, for convenience, I usually sub-space the plugin namespace with an inamespace for stuff that should only be used internally within the plugin, so as to hide it from users of the plugin.
此外,为了方便起见,我通常用一个i命名空间为插件命名空间子空间,这些命名空间应该只在插件内部使用,以便对插件的用户隐藏它。
This is how it works:
这是它的工作原理:
// An object to define utility functions and global variables on:
$.miniMenu = new Object();
// An object to define internal stuff for the plugin:
$.miniMenu.i = new Object();
Now I can just do $.miniMenu.i.globalVar = 3or $.miniMenu.i.parseSomeStuff = function(...) {...}whenever I need to save something globally, and I still keep it out of the global namespace.
现在我可以做$.miniMenu.i.globalVar = 3或$.miniMenu.i.parseSomeStuff = function(...) {...}每当我需要全局保存某些东西时,我仍然将它保留在全局命名空间之外。
回答by aesede
EDITThe question is about JavaScript, the answer is about jQuery, which is wrong. This is an old answer, from times when jQuery was widespread.
编辑问题是关于 JavaScript,答案是关于 jQuery,这是错误的。这是一个古老的答案,从 jQuery 流行的时代开始。
Instead, I recommend understandig scopesand closuresin JavaScript
Old, bad answer:With jQuery you can just do this, no matter where the declaration is:
旧的,糟糕的答案:使用 jQuery,您可以做到这一点,无论声明在哪里:
$my_global_var = 'my value';
And will be available everywhere. I use it for making quick image galleries, when images are spread in different places, like so:
并且将随处可用。当图像散布在不同的地方时,我用它来制作快速图片库,如下所示:
$gallery = $('img');
$current = 0;
$gallery.each(function(i,v){
// preload images
(new Image()).src = v;
});
$('div').eq(0).append('<a style="display:inline-block" class="prev">prev</a> <div id="gallery"></div> <a style="display:inline-block" class="next">next</a>');
$('.next').click(function(){
$current = ( $current == $gallery.length - 1 ) ? 0 : $current + 1;
$('#gallery').hide().html($gallery[$current]).fadeIn();
});
$('.prev').click(function(){
$current = ( $current == 0 ) ? $gallery.length - 1 : $current - 1;
$('#gallery').hide().html($gallery[$current]).fadeIn();
});
Tip: run this whole code in the console in this page ;-)
提示:在此页面的控制台中运行整个代码;-)
回答by Paul Dragoonis
Here is a basic example of a global variable that the rest of your functions can access. Here is a live example for you: http://jsfiddle.net/fxCE9/
下面是一个全局变量的基本示例,您的其余函数可以访问该变量。这里是一个活生生的例子:http: //jsfiddle.net/fxCE9/
var myVariable = 'Hello';
alert('value: ' + myVariable);
myFunction1();
alert('value: ' + myVariable);
myFunction2();
alert('value: ' + myVariable);
function myFunction1() {
myVariable = 'Hello 1';
}
function myFunction2() {
myVariable = 'Hello 2';
}
If you are doing this within a jquery ready() function then make sure your variable is inside the ready() function alongwith your other functions.
如果您在 jquery ready() 函数中执行此操作,请确保您的变量与其他函数一起位于 ready() 函数中。
回答by user3632465
Declare the variable outside of functions
在函数外声明变量
function dosomething(){
var i = 0; // can only be used inside function
}
var i = '';
function dosomething(){
i = 0; // can be used inside and outside the function
}
回答by robe007
The best way is to use closures, because the windowobject gets very, very clutteredwith properties.
最好的方法是使用closures,因为window对象的属性变得非常非常混乱。
Html
html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="init.js"></script>
<script type="text/javascript">
MYLIBRARY.init(["firstValue", 2, "thirdValue"]);
</script>
<script src="script.js"></script>
</head>
<body>
<h1>Hello !</h1>
</body>
</html>
init.js(Based on this answer)
init.js(基于这个答案)
var MYLIBRARY = MYLIBRARY || (function(){
var _args = {}; // private
return {
init : function(Args) {
_args = Args;
// some other initialising
},
helloWorld : function(i) {
return _args[i];
}
};
}());
script.js
脚本.js
// Here you can use the values defined in the html as if it were a global variable
var a = "Hello World " + MYLIBRARY.helloWorld(2);
alert(a);
Here's the plnkr. Hope it help !
这是plnkr。希望有帮助!

