Avoid JS global variable conflicts
I. Principles
1.1 Use anonymous functions to pack scripts
1.2 use namespace (multi-level)
Ii. Improvement Process
2.1 original data (both a. js and B. js have the global variable window. a, which leads to a conflict and the global variable belongs to window)
// A. js
<Script type = "text/javascript">
Var a = 123, B = "hello world ";
</Script>
// B. js
<Script type = "text/javascript">
Var a, c = "abc ";
</Script>
2.2 use anonymous functions (a in a. js and B. js are not global variables, but B in B. js cannot access B in a. js and cannot communicate with each other)
// A. js
(Function ()
{
Var a = 123, B = "hello world ";
})();
// B. js
(Function ()
{
Var a, c = "abc ";
})();
2.3 use global variables for Communication (using window. str as a global variable will lead to better global variables and poor maintenance)
Var str;
// A. js
(Function ()
{
Var a = 123, B = "hello world ";
Window. str =;
})();
// B. js
(Function ()
{
Var a, c = "abc ";
Alert (window. str );
})();
2.4 use a namespace
Var GLOBAL = {};
// A. js
(Function ()
{
Var a = 123, B = "hello world ";
GLOBAL. A. a =;
})();
// B. js
(Function ()
{
Var a, c = "abc ";
Alert (GLOBAL. A. );
})();