Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Closure" in Javascript using object references: where are "private variables" stored?

Disclaimer: this may be a silly question, but it's something that has got me confused while studying Javascript.

I recently ran across the paradigmatic method to create private variables using closure in Javascript, namely using a function that returns an object that has reference to "private variables" through its methods

var safebox = function() {
  var _privateVariable = "abcd";
    return {
    "accessFunction":function() {
    return _privateVariable;
    }
}();
safebox.accessFunction(); // "abcd"

That is to say, the mechanism of closure maintains the variable _privateVariable even after the enclosing function returns.

What happens if the private variable is an object to which a reference is maintained after the enclosing function returns?

var safebox = function () {
  var _secretObject = {"secret": "abcd"}
  return {referenceToSecretObject: _secretObject};

}();


console.log(safebox); // "abcd"
safebox.referenceToSecretObject.secret = "def";
console.log(safebox); // "def"

Here, as I understand it, ´_secretObject´ still exists, as we have a (shared) reference to it in ´safebox.referenceToSecretObject´. But this isn't closure (as I understand it). Is it just what it is, that the variable still exists because there is a reference to it (not garbage collected) even after the function returns? I am just confused because it seems close in form to closure, but perhaps I'm just seeing some resemblance that is purely coincidental.

like image 493
Cerulean Avatar asked Dec 06 '25 05:12

Cerulean


1 Answers

Inside the function you have:

  • A variable _secretObject which has a value that is a reference to an object
  • A second object with a property referenceToSecretObject which has a reference to the same object

You are calling that function and assigning the return value (the second object) to safebox.

At this point the function finishes.

What happens if the private variable is an object to which a reference is maintained after the enclosing function returns?

The variable _secretObject drops out of scope. There is nothing that can access it. The variable is cleaned up. It no longer exists.

The object _secretObject used to reference still exists because the second object still references it (and the second object is referenced by safebox).

If you were to then, for example, safebox = null then the reference to the second object would go away.

This would leave 0 references to the second object so it would be garbage collected.

This would get rid of the referenceToSecretObject so there would be 0 references to the first object.

It is at this point that the first object would be garbage collected.

like image 125
Quentin Avatar answered Dec 09 '25 22:12

Quentin