views:

46

answers:

1
window.global_array = new Array();  
window.example = function()  
{  
     var x = new Object();  
     x['test_property'] = 3;  
     global_array.push(x);  
}

Javascript gurus, please answer three questions:

  1. will javascript delete x at the end of scope when example() returns, or preserve it inside global_array.
  2. can I safely assume javascript works like 'everything is a reference' in python?
  3. are all VMs created equal or will GC rules vary by implementation.
+4  A: 
  1. Yes. x will be deleted, because its scope is limited to the function body (you used the var keyword, which ensures this. Variables declared without var will be global, even when within a function body). However, the value x had will continue to be present in global_array.
  2. Not entirely. Objects (arrays, too!) are passed as references, primitive values (like numbers) will be copied.
  3. GC will vary by implementation, but this should be none of your concern. JavaScript implementations will behave the same, unless there is a bug.

Since x is referencing an object, the assignment (through push()) is increasing the reference count. When x going out of scope at the end of the function, this would not decrease the reference count to 0, so the object will still be there - its only reference now from within global_array.

Tomalak