1

Take for example:

var myobj; // this will be the object


(function () {
    // private members
    var name = "my, oh my";


    // implement the public part
    // note -- no `var`
    myobj = {
        // privileged method
        getName: function () {
            return name;
        }
    };
}());


myobj.getName(); // "my, oh my”

from the JavaScript Patterns book by Stefanov.

If you were to use the Chrome console, how would you locate the variable name, without the privileged method?

Take for example this code:

var a_1 = function(){console.log(this)}

a_1();

The window object that it logs, you can browse to a_1 - see the image attached (link below)

console logging the window object

Could we do the same with name variable in the anonymous immediate function?

Let me know if I have constructed my question clearly.

1 Answers1

2

It seems that you're asking if the variable can be read in the console in Chrome.

The answer is yes. Type window.myobj into the console and expand the objects as shown below, and you'll see "my, oh my" under name.

window.myobj -> getName -> <function scope> -> Closure -> name;

If this was more than just a curiosity, and you were hoping for security via closure variables, you won't get it. There's no security in JavaScript.

cookie monster
  • 10,671
  • 4
  • 31
  • 45