简体   繁体   English

Javascript闭包是否始终保留范围变量?

[英]Does Javascript closure always retain scope variables?

I understand that code in closure can access variables & methods & arguments up the scope chain, but what happens if it doesn't use any of them ? 我了解闭包中的代码可以访问作用域链中的变量,方法和参数,但是如果不使用任何变量,会发生什么呢? do those variables still retained ? 这些变量仍然保留吗?

Consider this case : 考虑这种情况:

function f(){

  var a=[];
  for(var i=0;i<1000000;i++) a.push({});

  return function(){
     alert('Hi');
  };

}

var x = f();

Does variable a retained in memory even though the closure does not use it ? 是否变量a保留在内存中,即使关闭不使用它?

Thanks 谢谢

UPDATE: Seems there's no answer about 'trivial' closures. 更新:似乎没有关于“琐碎”闭包的答案。 So is it fair to assume that each and every closure ( even if it does nothing at all ) may retain in memory all the methods up the scope chain including their arguments , variables and inner functions ( until the closure is garbage collected )? 因此,可以合理地假设每个闭包(即使它什么也不做)可以将范围链中的所有方法(包括其参数,变量和内部函数)保留在内存中(直到闭包被垃圾回收)?

Also, about the 'possibly duplicate' question about node.js - to my knowledge node.js runs only on a dedicated environment that based on google's v8 JS engine. 另外,关于node.js的“可能重复”问题-据我所知,node.js仅在基于Google v8 JS引擎的专用环境中运行。 Here I'm talking about web-apps that will run in any modern browser ( in most cases ) 在这里,我谈论的是将在任何现代浏览器中运行的网络应用(大多数情况下)

When the interpreter chooses to free the memory it occupied is an implementation detail - there is no single javascript interpreter. 当解释器选择释放其占用的内存时,它是一个实现细节-没有单个javascript解释器。

Note that it's not always possible for the interpreter to know the variable is unused: 请注意,解释器并非总是可能知道未使用变量:

function f() {
    var a = 123

    return function(x) {
        alert(eval(x));  // if there's an eval, we have to hold onto all local variables
    };

}

f()('a')

Experimenting in the chrome console 在Chrome控制台中进行实验

var e = eval

var f = function(){
    var a = 123;
    
    return function() {
        return eval('a');
    };
};

var g = function(){
    var a = 123;

    return function() {
        return e('a');
    };
};


f()()  // 123
g()()  // ReferenceError

It appears that V8 is making optimizations based on the present of eval 看来V8正在根据eval的存在进行优化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM