Javascript嵌套函数初始化 [英] Javascript nested functions initialization
问题描述
我有一个javascript函数,其中(关闭)包含另一个javascript函数
I have a javascript function which contains another javascript function inside (closure)
function function1() {
$("button").bind("click", function () {
function2();
});
function function2() {
// code
};
};
我的问题:
当我多次调用function1()时,是否每次都会创建一次function2()(并保存在内存中)?还是共享?
When i call function1() for many times, does the function2() gets created each time (and saved in memory)? or it is shared?
function1
不用作构造函数,所以我不认为我应该使用 prototype
function1
is not used as a constructor, so i don't think i should use prototype
推荐答案
是的,每次执行 function1
时,都会创建 function2
,这可能是可以避免的低效率.
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);
};
因此, function2
定义了一次,并可能多次使用.
Thus, function2
is defined once and used, potentially, many times over.
您为此付出的代价是拒绝使 function2
能够访问在 function1
内部声明的所有var.如所给出的,不存在这样的var,所以您就可以了.
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.
这篇关于Javascript嵌套函数初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!