如何在JavaScript中声明全局变量?

时间:2010-07-28 10:38:09

标签: javascript global-variables

如何在JavaScript中声明全局变量?

6 个答案:

答案 0 :(得分:213)

如果必须在生产代码中生成全局变量(应该避免)始终声明明确

window.globalVar = "This is global!";

虽然可以通过省略var来定义全局变量(假设没有相同名称的局部变量),但这样做会生成隐式全局,这是一个不好的事情,并会在严格模式中生成错误。

答案 1 :(得分:52)

如果这是您要使用此变量的唯一应用程序,那么Felix的方法非常出色。但是,如果您正在编写jQuery插件,请考虑jQuery对象下所需的“命名空间”(稍后引用的详细信息......)变量和函数。例如,我正在研究一个名为miniMenu的jQuery弹出菜单。因此,我在jQuery下定义了一个“命名空间”miniMenu,并将所有内容放在那里。

当我谈论javascript命名空间时,我使用引号的原因是它们通常不是真正的命名空间。相反,我只使用javascript对象并将所有函数和变量作为此对象的属性。

另外,为方便起见,我通常使用i命名空间对插件命名空间进行子空间处理,以便只在插件内部使用,以便将其隐藏在插件的用户之外。

这是它的工作原理:

// 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(...) {...}。我仍然将它保留在全局命名空间之外。

答案 2 :(得分:21)

使用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();
});

提示:在此页面的控制台中运行此完整代码; - )

答案 3 :(得分:15)

以下是其余功能可以访问的全局变量的基本示例。以下是您的实例: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()函数一起位于其他函数内。

答案 4 :(得分:4)

在函数

之外声明变量
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
}

答案 5 :(得分:3)

最好的方法是使用 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 (基于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 as if it were a global variable
var a = "Hello World " + MYLIBRARY.helloWorld(2);

alert(a);

这里是plnkr。希望它有所帮助!

相关问题