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

时间:2022-10-08 00:41:19

How can I declare a global variable in JavaScript?

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

6 个解决方案

#1


209  

If you have to generate global variables in production code (which should be avoided) always declare 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 implicit global, which is a bad thing to do and would generate an error in strict mode.

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

#2


50  

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" miniMenu under jQuery, and I place everything there.

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

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 i namespace 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 = 3 or $.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(...){...}全局命名空间

#3


19  

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 ;-)

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

#4


15  

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()函数一起位于其他函数内。

#5


4  

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
}

#6


3  

The best way is to use closures, because the window object gets very, very cluttered with properties.

最好的方法是使用闭包,因为窗口对象变得非常非常混乱。

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

的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);

Here's the plnkr. Hope it help !

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

#1


209  

If you have to generate global variables in production code (which should be avoided) always declare 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 implicit global, which is a bad thing to do and would generate an error in strict mode.

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

#2


50  

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" miniMenu under jQuery, and I place everything there.

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

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 i namespace 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 = 3 or $.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(...){...}全局命名空间

#3


19  

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 ;-)

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

#4


15  

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()函数一起位于其他函数内。

#5


4  

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
}

#6


3  

The best way is to use closures, because the window object gets very, very cluttered with properties.

最好的方法是使用闭包,因为窗口对象变得非常非常混乱。

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

的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);

Here's the plnkr. Hope it help !

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