Skip to content Skip to sidebar Skip to footer

Javascript Nested Functions Initialization

I have a javascript function which contains another javascript function inside (closure) function function1() { $('button').bind('click', function () { function2();

Solution 1:

Each time you call function1, a new function2 is created and saved in memory, and is signed up as part of a click handler.

The function2's that are created by function1 can't get garbage collected as long as they could potentially be called through your click handler.


Solution 2:

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.


Post a Comment for "Javascript Nested Functions Initialization"