About JavaScript closures and refactoring

Source: Internet
Author: User

When I modified the bug, I accidentally remembered the concept of closure that the manager had told me, and I accidentally thought it could be applied to the code.

Is there a scene where one of your actions needs to be done after all async methods have been executed? However, you are troubled by when asynchronous methods are executed, and only write callbacks in each method, repeating the work in the callback?

For example, you need to trigger three async methods at an action, they are A (), B (), C (). We execute a,b,c in the D () method. Then we need to throw an action after the execution of the three methods, but how do we know when the three async methods are executed? And exactly how to throw it after the last method of execution?

//Async a    functionA (CB) {...
if (CB) CB (); } //Async B functionB (CB) {.....
if (CB) CB (); } //Asynchronous C functionC (CB) {.....
if (CB) CB (); } //Action functionaction () {...} //called by functionMain () {a (); b (); C (); Action (); }

Originally I was using a global variable count to record the number of executions, minus the number of executions in each method's callback. When count in a callback method is reduced to 0, the method is proven to be executed.

    varCount=3; //Async a    functionA () {... ..if(--count<=0) {action (); }    }    //Async B    functionB () {... ..if(--count<=0) {action (); }    }    //Asynchronous C    functionC () {... ..if(--count<=0) {action (); }    }    //called by    functionMain () {a ();        b ();        C (); //action ();}

Yes, this method is possible, but this method is a bit of a disadvantage, first count is a fixed value, you have to know beforehand how many methods to execute, that is, you have to count, if the new method, it will also change the value of count, it is clear that this and our "open-close" principle is the opposite. Second, each method is to write a string of the same code, reusability is too low, too many repetitive code. Finally, each method accesses global variables, which adds global resources, as our manager has said, because the logic inside the method pollutes the external or global code.

Understand the shortcomings of this writing, nature is to change.

"Code Encyclopedia" in the ' Table Query method ' has a high evaluation, that is, concise code, but also increased readability, in some scenarios or even improve the code performance of the weapon, why don't we use?

Initfun:function() {    /            /Initialize                var funarr = [A, B, c];                                             Funarr.foreach (function  (item) {                    item ();                })            }          

Okay, so how do you call callbacks after the execution of the three methods with the closure implementation exactly?

Before that, let's look at the characteristics of closures: Accessing external variables, preserving external variables.

Access to external variables is the ability to access external variables, parameters, local variables, or functions within a method. Keeping an external variable means that the external variable being accessed is detained in the context of the method, and each invocation method takes the context. In simple terms, this external variable that we are accessing is stored in the method's memory, similar to the one that comes with a global variable.

So how do we apply it to the code?

    //Async a    functionA () {...} //Async B    functionB () {...} //Asynchronous C    functionC () {...}
...... //Closure callsfunction Closurefun (Closurecount, CLOSURECB) {varCount =Closurecount; varcallback =CLOSURECB; return function () { if(!--count) {callback (); } } }, //Initializefunction Initfun () {varFunarr =[A, B, c]; //callback method After all async methods are executed varCallBack =function() {Console.log (' I am callback '); } //registering the closure code varTestclosurefun =Me.methods.closureFun (Funarr.length, callBack); Funarr.foreach (function(item) {Item (TESTCLOSUREFUN); }) },

In the initialization method, reference table Query method, the method is persisted in an array, write the callback method, and register it to the closure method. Funarr.length is the external variable that is accessed by the closure method, which is the number of times that will eventually run after the internal judgment of the closure, one method per run, the number minus one, and when all the methods are executed, count is 0, and the callback method is called.

This code is not contaminated to the global, the number of methods are automatically calculated, each method is extracted from the duplicate code, it is also a point of optimization.

Perhaps there are many more places to optimize, or perhaps my optimization is not particularly good, there are better optimization strategies. If someone knows and can guide twos, that is the honor of my humble.

Front-end rookie hope the great God guidance.

About JavaScript closures and refactoring

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.