JavaScript变量的生命周期 [英] Lifetime of JavaScript variables

查看:140
本文介绍了JavaScript变量的生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript中一个变量的生命周期,用var声明。
我相信,这绝对不符合预期。

 < script> 
function(){
var a;
var fun = function(){
// a被访问并被修改
}
}();


< / script>

这里JavaScript垃圾如何以及何时收集变量 a ?由于 a 是内部函数关闭的一部分,因此理想情况下不应该垃圾回收,因为内部函数 fun ,可以作为对外部上下文的引用传递。因此 fun 应该仍然能够从外部环境访问 a

如果我的理解是正确的,那么垃圾收集是如何发生的呢?它是如何保证有足够的内存空间的,因为将所有变量保存在内存中直到执行程序可能无法成立?

解决方案

ECMAScript规范没有指定垃圾收集器应该如何工作,它只是说如果标识符是可访问的(通过直接指针或封闭),它不应该被GCed。



查看这篇关于标识符解析,关闭,范围链接和ECMAScript垃圾回收的文章。



希望它有帮助


What is the lifetime of a variable in JavaScript, declared with "var". I am sure, it is definitely not according to expectation.

<script>
function(){
   var a;
   var fun=function(){
     // a is accessed and modified  
     }
}();


</script>

Here how and when does JavaScript garbage collect the variable a? Since a is a part of the closure of the inner function, it ideally should never get garbage collected, since the inner function fun, may be passed as a reference to an external context. So fun should still be able to access a from the external context.

If my understanding is correct, how does garbage collection happen then, and how does it ensure to have enough memory space, since keeping all variables in memory until the execution of the program might not be tenable ?

解决方案

The ECMAScript specification does not specify how the garbage collector should work, it only says that if an identifier is reachable (through a direct pointer or a closure), it shouldn't be GCed.

Check out this article about identifier resolution, closures, scope chaining and garbage collection in ECMAScript.

Hope it helps

这篇关于JavaScript变量的生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆