6

Take for example this code:

var test = (function(){
  var name = 'rar';
  return function foo(){
    console.log('test');
  };
}());

foo gets returned to test without any references to name in the inner scope. What happens to name? Is it destroyed? Or does it continue to exist and dangle with the returned function, but just can't be accessed? Would the first case be similar to doing the following, as if name was never part of the equation?:

var test = function foo(){
  console.log('test');
};

Here's another case:

var test2 = (function(){
  var name = 'rar';
  var age = '20';
  return function foo(){
    console.log(age);
  };
}());

age gets referenced by foo and will form a closure. However, name still isn't referenced by anything. What happens to name in this case? Is it destroyed? Or does it continue to exist and dangle with the returned function, but just can't be accessed?

Joseph
  • 117,725
  • 30
  • 181
  • 234
  • 2
    http://stackoverflow.com/a/864549/2269749 – BlitZ May 31 '13 at 06:03
  • @CORRUPT The answers seem to indicate that what happens depends on the implementation. So that means, in the worst case, `name` will stay, is it right? – Joseph May 31 '13 at 06:11
  • Yes. Browsers have different JS GC engines, each may act differently in this case. Consider `name = null` as an option, to prevent memory leaks. – BlitZ May 31 '13 at 06:13
  • 1
    `name = null;` might be done before scope ends. Should remove problems. – BlitZ May 31 '13 at 06:19
  • 2
    @JosephtheDreamer You might already know, but I think it's still worthwhile to point out that you can easily inspect a function's closure scope in chrome's dev tools and firefox's firebug. – Ye Liu May 31 '13 at 06:44

1 Answers1

4

In Chrome, name will be GCed; in FireFox, name is kept with the entire closure. IE? I don't know.

Ye Liu
  • 8,946
  • 1
  • 38
  • 34
  • Can I request for a reference as to why Chrome GCs `name` but not in Firefox? – Joseph May 31 '13 at 06:23
  • @JosephtheDreamer I don't have any reference, my answer is solely based on observation while working with browsers. – Ye Liu May 31 '13 at 06:27