如何在.js文件中声明一个全局变量 [英] How to declare a global variable in a .js file
问题描述
在所有 .js
文件中,我需要一些全局变量。 例如,考虑以下4个文件:
-
global.js
-
js1.js
-
js2.js
-
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:
global.js
js1.js
js2.js
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屋!