Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
462 views
in Technique[技术] by (71.8m points)

javascript - 如何在JavaScript中声明全局变量?(How to declare a global variable in JavaScript?)

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

  ask by Dancer translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

(如果必须在生产代码中生成全局变量(应该避免),请始终 明确声明它们:)

window.globalVar = "This is global!";

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 .

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...