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.

jotch
  • 5,416
  • 2
  • 12
  • 20

1 Answers1

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.

Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59
  • 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 May 16 '16 at 03:47
  • @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 May 16 '16 at 03:48
  • @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 May 16 '16 at 03:52
  • @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.. – Rajshekar Reddy May 16 '16 at 03:52