首页 文章

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

提问于
浏览
133

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

6 回答

  • 3

    如果必须在 生产环境 代码中生成全局变量(应该避免) always 声明它们 explicitly

    window.globalVar = "This is global!";
    

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

  • 210

    如果这是唯一的应用程序,你的方法非常好 . 但是,如果您正在使用jQuery弹出菜单,我在jQuery下定义了一个"namespace" 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(...) {...} ,而且我仍然将它保留在全局命名空间之外 .

  • 4

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

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

  • 51

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

  • 15

    在函数之外声明变量

    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
    }
    
  • 19

    最好的方法是使用 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 . 希望它有所帮助!

相关问题