Javascript closures in parsing

By Ann Kelly,2015-06-26 08:57
24 views 0
Javascript closures in parsing

    Javascript closures in parsing

    Today someone asked the questions about the closure of javascript, oneself also didn't read the related document, just vague answer.Answer after feeling so bad for yourself, be sure to understand javascript closures.Just in firefox developer community to see an article has closed packages at

    A, what is a closure?

    Closures have independent independent variable refers to the function, that is defined in the closure function can memory when it creates the "environment".

    Second, the grammar scope

    Look at the following functions

    Js code



    In the init () function () to define a variable name is the name of temporary

    variables, and then define a name for the displayName internal function.The inner

    function only within the init method is available, no other way to call, you see

    displayName did not own a local variable in a function, however it can access to the

    outsourced function variable functions that use the variable - you can use the parent.

    We change the above code

    Js code



    This is an example of scope, in javascript, variable scope is nested function can

    access the external variables.

    Third, the closure

    Let's look at an example below

    Js code


    Run the code as well as the result of the above, the code looks awkward, but normal operation, we all know that the scope of a function only available at run time, when the init method run after we think have failed, not with the name variable, but there is no problem, while running is corresponding to the name variable is not actually that is not available have failed.

    Because the init has already become a closure, closure of a particular object, it has two parts: function and create a functional environment, environment created by the closure in the scope of any local variables, - the above we can say the init is a closure, created by the displayName function and closure time of name = "dongtian".

    See below an adder a closure of writing:

    Js code



    This example we defined the subAdd () function, with a parameter x, and returns a new function, returned by the function with a parameter and return the x and y and y.Essentially subAdd function () function is a factory, it was created and should specify a value and contains a sum function.In the above example we created by this function factory two function a parameters 2 sum a 5 sum, from which we can see that the two functions are closure, they Shared function definition and they are in different environments.

    The operation result is pop up 4 and 8

    Four, why use a closure

    That's the theory - but closure really useful?Let's take a look at the closure of practical significance.Closures allow the function and operation of some of the data (environment) link up.It is similar to the object-oriented programming.In the surface of object programming, object allows us to some of the data (attribute of an object) that is associated with one or more methods.

    Therefore, as a general rule, you can use only one method of object, closures can be used.

    In the Web, you may want to do this is very common situation.Most of what we write Web JavaScript code are event driven - define a certain behavior, and then add it to the user to trigger events (such as click or buttons).We usually add our code for the callback: executive function in response to the event.

    The following is an actual example: suppose we want to add some can adjust the font size on the page button.A method based on pixels specified body element of the font, size, and then through a relative to other elements in the em unit Settings page (for example, the header) font size:

    The Html code

    1. body {

    2. font-family: Helvetica, Arial, sans-serif;

    3. font-size: 12px;

    4. }


    6. h1 {

    7. font-size: 1.5em;

    8. }

    9. h2 {

    10. font-size: 1.2em;

    11. }

    body {

     font-family: Helvetica, Arial, sans-serif;

     font-size: 12px;


h1 {

     font-size: 1.5em;


    h2 {

     font-size: 1.2em;


    Our interactive text size button can change the font of the body element - the size

    attribute, and due to the unit, we use the other elements in the page will adjust


    The following is a JavaScript:

    Js code

    1. function makeSizer(size) {

    2. return function () {

    3. = size + 'px' ;

    4. };

    5. }


    7. var size12 = makeSizer(12);

    8. var size14 = makeSizer(14);

    9. var size16 = makeSizer(16); function makeSizer(size) {

     return function() { = size + 'px';



var size12 = makeSizer(12);

    var size14 = makeSizer(14);

    var size16 = makeSizer(16);

    Size12, size14 and size16 to adjust the body text accordingly to 12,14,16 pixels

    of the function.We can add them to the button (link) here.As shown below:

    Js code

    1. document.getElementById( 'size-12' ).onclick = size12;

    2. document.getElementById( 'size-14' ).onclick = size14;

    3. document.getElementById( 'size-16' ).onclick = size16; document.getElementById('size-12').onclick = size12;

    document.getElementById('size-14').onclick = size14;

    document.getElementById('size-16').onclick = size16;

    The Html code

    1. < a href = "#" id = "size-12" > 12

    2. < a href = "#" id = "size-14" > 14

    3. < a href = "#" id = "size-16" > 16




    Five, the closure was used to simulate a private method

    A number of languages such as Java, support the method statement for the

    private, that they can only be invoked by other methods in the same class.

    , JavaScript does not provide native support, but you can use closures simulation

    private method.Private method is not only beneficial to restrict access to code: also

    provides a powerful ability to manage the global namespace, method to avoid

    non-core disturb public interface part of the code.

    The following example shows how to use the closure to define public function,

    and it can access private functions and variables.Also known as this way

    Js code

    1. var Counter = ( function () {

    2. var privateCounter = 0;

    3. function changeBy(val) {

    4. privateCounter += val;

    5. }

    6. return {

    7. increment: function () {

    8. changeBy(1);

    9. },

    10. decrement: function () {

    11. changeBy(-1);

    12. },

    13. value: function () {

    14. return privateCounter;

    15. }

    16. }

    17. })();


    19. console.log(Counter.value()); /* logs 0 */

    20. Counter.increment();

    21. Counter.increment();

    22. console.log(Counter.value()); /* logs 2 */

    23. Counter.decrement();

    24. console.log(Counter.value()); /* logs 1 */ var Counter = (function() {

     var privateCounter = 0;

     function changeBy(val) {

     privateCounter += val;


     return {

     increment: function() {



     decrement: function() {



     value: function() {

     return privateCounter;




console.log(Counter.value()); /* logs 0 */



    console.log(Counter.value()); /* logs 2 */


    console.log(Counter.value()); /* logs 1 */

    There are so many details.In the example of the past, each closure has its own environment;And this time we only created an environment, Shared by three functions: Counter. Increment, Counter. The decrement and Counter value.

    The Shared environment created in an anonymous function in vivo, immediately once the function is defined.Environment contains two private items: called privateCounter variable and function called changeBy.These two can direct access to the outside the anonymous functions.Must through anonymous wrapper returned three public functions to access.

    The three public functions are sharing the same environment of closures.Thanks to the lexical scope of the scope of the JavaScript, they can access privateCounter variable and changeBy function.

Report this document

For any questions or suggestions please email