Avoid JS global variable conflicts

Source: Internet
Author: User

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. );
})();

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.