如何在.js文件中声明一个全局变量 [英] How to declare a global variable in a .js file

查看:939
本文介绍了如何在.js文件中声明一个全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在所有 .js 文件中,我需要一些全局变量。 例如,考虑以下4个文件:


  1. global.js

  2. js1.js

  3. js2.js

  4. js3.js

我可以在 global.js 中声明3个全局变量,并在任何其他3 .js 文件中访问它们考虑到我将所有上述4个文件加载到一个HTML文档?



有人可以告诉我这是可能的还是有解决方法来实现这一目标?

解决方案

只需在函数作用域外的global.js中定义变量:

  // global.js 
var global1 =我是全球性的!;
var global2 =我就是这样!;

//其他js文件
函数testGlobal(){
alert(global1);
}

为了确保工作正常,您必须包含/链接到global.js在尝试访问该文件中定义的任何变量之前:

 < html> 
< head>
<! - 首先包含global.js - >
< script src =/ YOUR_PATH / global.jstype =text / javascript>< / script>
<! - 现在我们可以引用变量,对象,函数等
在global.js中定义 - >
< script src =/ YOUR_PATH / otherJsFile.jstype =text / javascript>< / script>
< / head>
[...]
< / html>

当然,您可以在关闭< body> -tag之前链接脚本标记如果您不希望js文件的加载中断初始页面加载。


I need a few global variables that I need in all .js files.

For example, consider the following 4 files:

  1. global.js
  2. js1.js
  3. js2.js
  4. js3.js

Is there a way that I can declare 3 global variables in global.js and access them in any of the other 3 .js files considering I load all the above 4 files into a HTML document?

Can someone please tell me if this is possible or is there a work around to achieve this?

解决方案

Just define your variables in global.js outside a function scope:

// global.js
var global1 = "I'm a global!";
var global2 = "So am I!";

// other js-file
function testGlobal () {
    alert(global1);
}

To make sure that this works you have to include/link to global.js before you try to access any variables defined in that file:

<html>
    <head>
        <!-- Include global.js first -->
        <script src="/YOUR_PATH/global.js" type="text/javascript"></script>
        <!-- Now we can reference variables, objects, functions etc. 
             defined in global.js -->
        <script src="/YOUR_PATH/otherJsFile.js" type="text/javascript"></script>
    </head>
    [...]
</html>

You could, of course, link in the script tags just before the closing <body>-tag if you do not want the load of js-files to interrupt the initial page load.

这篇关于如何在.js文件中声明一个全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆