如何在JavaScript中声明全局变量 [英] How to declare a global variable in JavaScript

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

问题描述

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

How can I declare a global variable in JavaScript?

推荐答案

如果必须在生产代码中生成全局变量(应避免使用),则始终声明明确 >:

If you have to generate global variables in production code (which should be avoided) always declare them explicitly:

window.globalVar = "This is global!";

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

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.

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

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