简体   繁体   English

关于在JavaScript中定义全局变量

[英]About defining global variables in JavaScript

As per my understanding , in ES6 we can define global variables in 2 ways 据我了解,在ES6中,我们可以通过2种方式定义全局变量

var global1 = '1'; // CASE 1

In this case "global1" is set as a property of DOM window object , so window.global1 will print "1". 在这种情况下,将“ global1”设置为DOM窗口对象的属性,因此window.global1将输出“ 1”。

let global2 = '2'; // CASE 2

In this case "global2" is NOT set as a property of DOM window object , so window.global2 will print undefined. 在这种情况下,“ global2”未设置为DOM窗口对象的属性,因此window.global2将打印未定义。

My question is how to achieve case 2 in case of ES5. 我的问题是在ES5情况下如何实现情况2。

You can't. 你不能 It is possible in ES6 because let and const declarations are stored in their own global environment that isn't tied to the global object. 在ES6中这是可能的,因为letconst声明存储在与全局对象无关的它们自己的全局环境中。 If you're working with ES5, that mechanism does not exist. 如果您使用的是ES5,则该机制不存在。

Generally global variables, in either approach, are frowned up on in JS codebases though. 通常,无论哪种方式,全局变量都不会在JS代码库中使用。 Ideally you's want to use a module system alongside Webpack to bundle up your code so that each file has its own scope, with things linked with explicit imports and exports. 理想情况下,您希望与Webpack一起使用模块系统来捆绑代码,以使每个文件都有自己的作用域,并与明确的导入和导出关联。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM