Javascript nested functions initialization

情到浓时终转凉″ 提交于 2021-02-11 15:57:57

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/19251479/javascript-nested-functions-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!