Initializing Javascript Nested Functions

advertisements

I have a javascript function which contains another javascript function inside (closure)

function function1() {
    $("button").bind("click", function () {
        function2();
    });

    function function2() {
        // code
    };
};

My question:

When i call function1() for many times, does the function2() gets created each time (and saved in memory)? or it is shared?

function1 is not used as a constructor, so i don't think i should use prototype


Yes, function2 would be created each time function1 is executed, which is possibly an avoidable inefficiency.

The code in the question would execute more efficiently as follows :

function function2() {
    // code
};
function function1() {
    $("button").bind("click", function2);
};

Thus, function2 is defined once and used, potentially, many times over.

The price you pay for this efficiency is to deny function2 the opportunity of accessing any vars declared inside function1. As given, no such vars exist, so you would be OK.