Summary of JS Modular programming

Source: Internet
Author: User

As we all know, the variable in JS (variable) has its scope, for example: variables defined in the function are not visible outside the function, and variables defined outside the function (no var modifier) are global variables and can be accessed anywhere in the JS program. Well, in fact we work in the process, the business logic is more, and a business logic contains multiple functions, sharing between functions of a variable, so the problem arises, if another business logic accidentally defined or modified this variable, it will cause this global variable is contaminated, the previous business logic will be dirty read , the process test is as follows:

A very long page script contains two sub-business processes 1 and 2, the business handler 1 needs to define two functions and a variable, a function to set the variable, and a function to read the output variable, as follows:

1/*Page business logic 1***begin*****/23//Define a global variable for each function in logic 1 to share with 4 var test = 0; 5 function Setflag () {; 7 } 8 function Displayflag () {  Console.log (test); }11 12 /***** page business logic 1***end*****/    

Other Business handler scripts:

*/* * ..... ..... ..... ...   ..... ............. * Intermediate business logic, long-length * ..... ..... ....... ................... */

Business Handler 2 begins, logic processing also defines two functions and a variable, a function to set variables, a function to read variables for other processing, unfortunately, this global variable takes the same name as business logic 1:

1/*Page business logic 2***begin*****/23//Define a global variable for each function in logic 1 to share with 4 var test = 0; 5 function setvarable () {  6 test = 1; 7 } 8 function Displayv ( { Console.log (test); }11 12 /***** page business logic 2***end*****/    

The program process takes logic 2 and then logic 1, and an unexpected event occurs:

1 setvarable ();   // Logic 2 accidentally modified the value 3 Displayflag ();  //Error: Expected output 1, but dirty read 2    

The output results are as follows:

Obviously, the actual output is not the desired result, in addition to the other case, if a JS script is shared as a common script block, call (introduce) this script block in many places, it is also very easy to appear this problem.

The advent of modular Programming (module) solves this problem, but in addition to the modular programming there are several other features:

1. Maintenance of a clean front-end script of the variable environment, to protect the scope of the defined global variables are not outside the scope of the program pollution;

2. The reusability of front-end scripts is greatly improved, readability and maintainability are further enhanced;

3. You can combine multiple module scripts and abstract them into a common scripting library to improve the efficiency of code development.

As I said earlier, the function is not visible outside of the variable functions defined in it (that is, not available), in order to protect the scope of the variable environment, this is the result we need, so the entire business processing logic into a function implementation can implement a module definition, rewrite the above logic 1 and Logic 2 code as follows:

1/*Page business logic 1********/2functionHandleone () {3var test = 0;4This.setflag =function() {5 test = 1;6}7This.displayflag =function() {8 Console.log ("This is the variable value in logic 1:" +Test);9}10//Returns the This object to access the functions defined in the module11ReturnThis;12}1314/*15* ..........................................16* Intermediate business logic, very lengthy17* ..........................................18*/1920/*Page business logic 2********/21stfunctionHandletwo () {22VarTest23This.setvarable =function() {Test = 2;25}26THIS.DISPLAYV =function() {Console.log ("This is the variable value in Logic 2:" +Test);28}29//Returns the This object to access the functions defined in the module30ReturnThis31 }32 33 var H1 = Handleone (); var H2 = Handletwo (); 36 h2.setvarable (); // Logic 2 modifies its own variable 37 38 H1.displayflag (); // logic 1 outputs its own variable 39 40 h2.displayv (); // logic 2 output its own variable        

The output results are as follows:

By the way, in the modular programming, each module internal use of common variables are well protected, not to receive other external logic processing interference, but the above procedure requires us to define two function modules, if we do not want to define any additional intermediate variables, we can use anonymous function to re-implement the above process, The code is rewritten as follows:

1/*Page business logic 1********/2var H1 = (function() {3var test = 0;4This.setflag =function() {5 test = 1;6}7This.displayflag =function() {8 Console.log ("This is the variable value in logic 1:" +Test);9}10//Returns the This object to access the functions defined in the module11ReturnThis;12} ());1314/*15* ..........................................16* Intermediate business logic, very lengthy17* ..........................................18*/1920/*Page business logic 2********/21stvar H2 = (function() {22VarTest23This.setvarable =function() {Test = 2;25}26THIS.DISPLAYV =function() {Console.log ("This is the variable value in Logic 2:" +Test);28}29 // Returns the This object to access the function defined in module 30 return this; } ()); 32 33 h2.setvarable (); // Logic 2 modifies its own variable 34 35 H1.displayflag (); // logic 1 outputs its own variable 36 37 h2.displayv (); // logic 2 output its own variable        

the above is a modular package implemented with anonymous functions, the output is the same as the entity function, is not more concise than the entity function?!

Note: In the above procedure we return the This object in each module because we need to invoke the function in the module in the subsequent logic, if the module handler does not need to be called by external logic in practice, but only outputs the result inside the module. We simply return the result value of the module's final processing or do not need to return the statement, according to the specific situation of specific analysis.

Through the above examples, we can summarize the general idea of Modularization:

1. The definition of a series of related functions and variables is placed in a function (anonymous function also line) can form a module, the scope of variables and functions in the module is confined to the inside of the module, the external cannot be directly called, the module can return the processing result of the given logic.

2. If you need to provide an interface to a function or variable in the calling module outside the module, you will need to mark the definition of the function or variable in the module with this and then return the this object at the end of the module (the This object in the function refers to the Window object).

The modular programming idea is as follows:

1//A modular approach to entity functions2functionMoudle () {34VarTheresult;56//Do something here78//This sentence is optional and returns the final processing result.9ReturnTheresult;10}11//Executes the module procedure and can receive return values when there is a return value12Moudle ();13 14 // modular approach to anonymous functions 15 var result = ( function {16 var Theresult; 18 //do something Here19 20 // this sentence is optional and returns the final processing result 21 return  Theresult; 22});             

Article from http://www.360doc.com/content/15/0810/21/27084883_490826869.shtml

Summary of JS Modular programming

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.