1

I need to access a private variable from an anonymous function. This anonymous function is set by the following:

coolObject = new (function(){
    this.public = "public";
    var private = "secrets";

    // General functions here, no getter or setter for private
})();

I can easily read and write to coolObject.public by doing console.log(coolObject.public) or coolObject.public = "newValue", but how can I do the same to the private variable? Another thing is that I cannot add code to the constructor, coolObject will always be initially defined like this.

So, to sum everything up, is there a way I can access a private variable from a anonymous function in JavaScript, and if so, how?

Edit: I have tried creating getters and setters by doing coolObject.getPrivate = function(){return private;};, but that doesn't work.

3
  • 4
    Without any changes to coolObject constructor - no Commented May 16, 2016 at 3:40
  • 2
    Such variables are called "private" for a reason. By the way, the fact that the function is anonymous is irrelevant here. Commented May 16, 2016 at 3:41
  • 1
    Make it not private? Seems to be the point of a private variable is working as intended there. Commented May 16, 2016 at 3:42

1 Answer 1

2

No it's not possible without changing the code which you have.

As you mentioned you cannot change the code, you cannot read the private variable. The reason for making a variable private is to make sure you cannot read and write it from outside the scope. If at all that is possible then the meaning and the reason of private variable is lost.

Sign up to request clarification or add additional context in comments.

4 Comments

What? People create getters and setters to private variables all the time. It in no way violates the reason for the variable being private. It's called encapsulation.
@4castle - Yes, but from outside the object you can't access the variable itself, all you can do is call the getter and setter. (And in this case the OP said they can't change the constructor function, so they can't add a getter or setter.)
@nnnnnn I'm just objecting to their description of a private variable. In many cases, it isn't done simply to restrict access to the variable, it's done for encapsulation. It's the difference between "reason" and "definition".
@4castle the OP wants to ab able to access the variable without making any changes to the code he provided. So given this code if at all the private variable is made accessible then it violates the purpose of private variable. But yes with code changes it can be done..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.