问题
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