如何在.js文件中声明全局变量

我需要所有.js文件中都需要的一些全局变量。

例如,考虑以下4个文件:

  1. global.js

  2. js1.js

  3. js2.js

  4. js3.js

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

有人可以告诉我这是否可行吗,或者有解决的办法吗?


一只斗牛犬
浏览 2036回答 3
3回答

拉丁的传说

只需在函数范围之外的global.js中定义变量:// global.jsvar global1 = "I'm a global!";var global2 = "So am I!";// other js-filefunction testGlobal () {&nbsp; &nbsp; alert(global1);}为确保此方法有效,您必须先包含/链接到global.js,然后再尝试访问该文件中定义的任何变量:<html>&nbsp; &nbsp; <head>&nbsp; &nbsp; &nbsp; &nbsp; <!-- Include global.js first -->&nbsp; &nbsp; &nbsp; &nbsp; <script src="/YOUR_PATH/global.js" type="text/javascript"></script>&nbsp; &nbsp; &nbsp; &nbsp; <!-- Now we can reference variables, objects, functions etc.&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;defined in global.js -->&nbsp; &nbsp; &nbsp; &nbsp; <script src="/YOUR_PATH/otherJsFile.js" type="text/javascript"></script>&nbsp; &nbsp; </head>&nbsp; &nbsp; [...]</html>当然,如果您不想让js文件的加载中断初始页面加载,则可以在结束<body> -tag之前的脚本标签中进行链接。

慕沐林林

推荐的方法是:window.greeting = "Hello World!"然后,您可以在任何函数中访问它:function foo() {&nbsp; &nbsp;alert(greeting); // Hello World!&nbsp; &nbsp;alert(window["greeting"]); // Hello World!&nbsp; &nbsp;alert(window.greeting); // Hello World! (recommended)}首选此方法有两个原因。目的是明确的。var关键字的使用很容易导致声明全局变量vars,而全局变量原本是本地变量,反之亦然。对于许多Javascript开发人员来说,这种变量作用域是一个混淆点。因此,作为一般规则,我确保所有变量声明都以关键字var或prefix开头window。您还可以标准化语法以这种方式读取变量,这意味着局部作用域var不会破坏全局变量,var反之亦然。例如,这里发生的事情是模棱两可的:&nbsp;&nbsp;greeting = "Aloha";&nbsp;function foo() {&nbsp; &nbsp; &nbsp;greeting = "Hello"; // overrides global!&nbsp;}&nbsp;function bar(greeting) {&nbsp; &nbsp;alert(greeting);&nbsp;}&nbsp;foo();&nbsp;bar("Howdy"); // does it alert "Hello" or "Howdy" ?但是,这更加简洁,而且不易出错(您实际上不需要记住所有变量作用域规则):&nbsp;function foo() {&nbsp; &nbsp; &nbsp;window.greeting = "Hello";&nbsp;}&nbsp;function bar(greeting) {&nbsp; &nbsp;alert(greeting);&nbsp;}&nbsp;foo();&nbsp;bar("Howdy"); // alerts "Howdy"

qq_笑_17

你试过了吗?如果您这样做:var HI = 'Hello World';在中global.js。然后执行:alert(HI);在js1.js它会很好。您只需要global.js在HTML文档的其余部分之前添加。唯一的问题是您必须在窗口范围内(而不是在任何函数内)声明它。您可以修改var零件并以这种方式创建它们,但这不是一个好习惯。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript