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:
- will javascript delete x at the end of scope when example() returns, or preserve it inside global_array.
- can I safely assume javascript works like ‘everything is a reference’ in python?
- are all VMs created equal or will GC rules vary by implementation.
xwill be deleted, because its scope is limited to the function body (you used thevarkeyword, which ensures this. Variables declared without var will be global, even when within a function body). However, the valuexhad will continue to be present inglobal_array.Since
xis referencing an object, the assignment (throughpush()) is increasing the reference count. Whenxgoing 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 withinglobal_array.