我如何在JavaScript中声明全局变量?
如果您必须在生产代码中生成全局变量(应该避免这样做),始终要明确地声明它们:
window.globalVar = "This is global!";
在JavaScript中,如果仅仅省略var
关键字(假设没有同名的局部变量),也可以定义全局变量。但是这样做会创建一个隐式全局变量,这种方式是不好的,而且在严格模式下还会产生错误。
miniMenu
,并将所有内容放置在那里。// 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();
现在我只需执行$.miniMenu.i.globalVar = 3
或者$.miniMenu.i.parseSomeStuff = function(...) {...}
即可在需要时全局保存一些内容,而且仍然不会污染全局命名空间。
delete $.miniMenu
)。可以吗? - Kunj$.miniMenu
。 - Tomas Aschan注意:问题是关于JavaScript的,而这个答案是关于jQuery的,这是错误的。这是一个旧的答案,在jQuery广泛使用时。
使用jQuery,无论声明在哪里,您都可以这样做:
$my_global_var = 'my value';
并且将可在任何地方使用。
我用它来制作快速的图像库,当图片分散在不同的地方时,就像这样:
$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();
});
提示:在此页面的控制台中运行整个代码;-)
$current = 0;
,后面的代码就无法工作。 - harrrrrrry以下是一个全局变量的基本示例,你的其余函数可以访问该变量。这里有一个实时示例供您参考: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';
}
如果您在jQuery的ready()函数中进行此操作,请确保您的变量与其他函数一起位于ready()函数内部。最好的方法是使用 closures
,因为 window
对象会有很多属性,使得它非常杂乱无章。
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)
var MYLIBRARY = MYLIBRARY || (function(){
var _args = {}; // Private
return {
init : function(Args) {
_args = Args;
// Some other initialising
},
helloWorld : function(i) {
return _args[i];
}
};
}());
script.js
// Here you can use the values defined in the HTML content as if it were a global variable
var a = "Hello World " + MYLIBRARY.helloWorld(2);
alert(a);
将变量声明在函数外部
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
}
window
只在浏览器中可用。你能否编辑你的答案,使其在所有环境中都能工作?请参阅 如何在 JavaScript 中获取全局对象? - Michał Perłakowskiglobal
对象与浏览器中的window
对象相同。 - GiantBooley