Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a scope terminate when no references are returned?

Tags:

javascript

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?

like image 967
Joseph Avatar asked May 31 '13 05:05

Joseph


1 Answers

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

like image 160
Ye Liu Avatar answered Oct 29 '22 02:10

Ye Liu