嵌入函数问题
例如:
//global vars
var g1,g2,g3;
function a(p1,p2,p3){
//local vars
var a1,a2,a3;
return function(){
//an embed function, looks like dynamic defined at runtime
}
}
var f1 = a(1,2,3)
var f2 = a(4,5,6)
f1()
f2()
我的问题是,f1和f2是否指向内存中的相同代码,为什么它们接缝不同的函数?每次调用 a 时,函数 a 是否都会花费时间来创建嵌入函数?
而且GC的工作方式也很有趣,a执行完后,a的局部变量不会被GC,而必须是返回的embed函数被GC后才被GC,因为返回的embed函数仍然可以调用函数a的局部变量。
for example:
//global vars
var g1,g2,g3;
function a(p1,p2,p3){
//local vars
var a1,a2,a3;
return function(){
//an embed function, looks like dynamic defined at runtime
}
}
var f1 = a(1,2,3)
var f2 = a(4,5,6)
f1()
f2()
my question is , is f1 and f2 point to the same code in memory, why they seams diffrent function? does function a spend time to create the embed function when a is call each time?
and GC works also very intresting, local vars of a will not be GC after a executed, It must be GC after the returned embed function GCed, cause of returned embed function still can invoke the local vars of function a.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
回答你的问题:
函数之间的差异语句和表达式
闭包
有关闭包的更多信息,请参阅此问题 和答案。
To answer your questions:
Difference between Function Statement and Expression
Closures
For more on closures see this question and the answers.
它们并不指向同一个函数。
是的,每次调用
a
函数时,都会创建并返回一个新的内部函数。是的,这就是所谓的闭包。内部函数可以访问创建它的执行环境的所有变量。
They don't point to the same function.
Yes, every time you call the
a
function, a new inner function will be created and returned.Yes, that's called closure. The inner function has access to all variables of the execution environment in which it was created in.
正如您所提到的,嵌入式函数可以访问局部变量。这称为闭包。
As you mentioned, embedded functions have access to the local variables. This is called a closure.