Consider I have the below webpage written in HTML (body section only):
<body>
<p>
...
</p>
<script>
function fn() {
// do stuff
}
</script>
</body>
Now, if I replace the innerHTML
of document.body
from JavaScript with say, a div, so that the body part becomes:
<body>
<div>
...
</div>
</body>
... then is the fn
object eligible for garbage collection if no references to it exist anywhere in the rest of the code (any context)?
Some high-level languages, such as JavaScript, utilize a form of automatic memory management known as garbage collection (GC).
WARNING Assigning an object or array as a constant means that value will not be able to be garbage collected until that constant's lexical scope goes away, as the reference to the value can never be unset. That may be desirable, but be careful if it's not your intent!
It would be subject to garbage collection if no other references were made to it from any context. However, there is one small reference that is holding on to that function, the global window object. This is because the function (and entire script section shown) is scoped globally. This reference will still exist even if the entire document.body's innerHTML is replaced.
There are only a few ways to free the object shown in your exact example from the global object and make it eligible for collection. Deleting the property on the global object is not an option because it was declared as a function and not as a property.
window.fn = [][0];
(undefined shortcut)Quick note on garbage collection, it occurs when the browser feels that it is necessary, and not immediately after an object has no references (or at least, not usually - this may happen from time to time).
Just tested this out, and interestingly, no.
http://jsfiddle.net/wah754La/1/
Test code:
body:
<script type="text/javascript">
function foo () {
// i exist!
}
</script>
and on load, this is run:
document.body.innerHTML = '';
console.log(foo);
// logs 'function foo()'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With