GBarroso GBarroso - 6 months ago 9
Javascript Question

Accessing "private" variables in javascript

Let's say I have the following class:

function MyClass(){

this.public = function(){
console.log(private);
};

var private = 10;
}


var test = new MyClass;

test.public(); // logs 10
test.private; // undefined


I want to know if I can access the private variable from the outside. Looking at chrome's console it seems to be possible, since its context is shown:

enter image description here

EDIT: Just to clarify: I know how to properly expose it. Just want to be sure if there isn't some hacky way to access it.

Answer

Your private variable is local to that function scope and within Javascript, there is no access to variables inside a scope from outside the scope. You can ONLY access it from within the scope. There are no ways to get around this from Javascript code itself.

What a debugger can do (which has access to the VM internals) is different than what regular Javascript code can do. The debugger can look inside of scopes, but JS code from outside the scope cannot.

Obviously you can make an accessor for it, but without an accessor, there is no way to get to it from the outside.