Avoid JS global variable conflicts

Source: Internet
Author: User


First, the principle
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, which causes conflicts, global variables belong 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.js and a in b.js are not global variables, but the B in a.js cannot be accessed in b.js, there is no way to communicate)

// 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 can cause global variables to become better and more difficult to maintain)

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    a=123,b= "Hello World" ; GLOBAL. A.A  =A;}) (); // b.js  (function    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.