Data independence for "JavaScript" closure applications

Source: Internet
Author: User

In the normal development, there are always some ways we can be useful in different places, so we will encapsulate these methods. When we need to develop a function, we need to use a combination function (there is a link between multiple functions, that is, there is one or more common global variables) and this combination function needs to be called in many places. If you simply set this combination function to a global function whose common variables are set to global variables, you will find a problem: I reference this combination function in a function, the global variable of the function after the reference has been obtained a data a, when we in the B function and trigger the combination function, Globally the global variable is modified to B, so that when we lose the data A. The use of closures can be a good solution to this problem, examples are as follows:

The code implements two kinds of "stand-alone" counter function Createcounter () {var counter = 0;return function () {Counter ++;console.log ("Number of events: "+ counter);}} var counter1 = Createcounter (), var counter2 = Createcounter (); Counter1 ();//number of Events:1counter1 ();//number of even Ts:2counter2 ();//number of Events:1counter1 ();//number of Events:3

Data independence for "JavaScript" closure applications

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.