Avoid JS global variable conflict

Source: Internet
Author: User
Tags anonymous

I. Principles

1.1 Wrapping the script with anonymous functions
1.2 Using namespaces (multilevel)


Ii. the process of improvement

2.1 Raw Data (A.js and b.js have global variable window.a, resulting in conflict, 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 Using anonymous functions (A is not a global variable in a.js and b.js, but cannot be accessed in the B.js a.js B, no communication)

A.js
(Function ()
{
var a=123,b= "Hello World";
})();

B.js
(Function ()
{
var a,c= "abc";
})();

2.3 Using global variables for communication (using WINDOW.STR as a global variable, resulting in global variables becoming better and less maintainable)

var str;
A.js
(Function ()
{
var a=123,b= "Hello World";
Window.str=a;
})();

B.js
(Function ()
{
var a,c= "abc";
alert (WINDOW.STR);
})();

2.4 Using namespaces

var global={};
A.js
(Function ()
{
var a=123,b= "Hello World";
GLOBAL. A.a=a;
})();

//b.js
(function ()
{
var a,c= "abc";
Alert (GLOBAL. A.A);
}) ();

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.