0

I have an JavaScript library that implements "private fields" with closures, along the lines of:

function makePublicInterface()
{
    var private = 17;

    return {
        foo: function() { console.log(private); }  
    };
}

and I have an object returned by that function:

    var public = makePublicInterface();

Is there a way, given 'public', to somehow access 'private'? Chrome devtool certainly can, but I don't see a way to do it programmatically, there is nothing in either Object or Function to do that.

This is purely a language question, I can add an accessor method to this particular library just fine.

Vladimir Prus
  • 4,600
  • 22
  • 31
  • No there is not, the point is to close the variables in, and not make them accessible outside the closure, so there's no workaround other than creating accessible methods that exposes the variables. – adeneo Jan 13 '15 at 19:04
  • It's called **private** for a reason. However, you could do `function getPrivate(instance){var l=console.log, r; console.log=function(p){r=p}; instance.foo(); console.log=l; return r;}` – Bergi Jan 13 '15 at 19:17
  • possible duplicate of [Accessing variables trapped by closure](http://stackoverflow.com/questions/4472529/accessing-variables-trapped-by-closure) – zamnuts Jan 13 '15 at 19:18

2 Answers2

0

There is no way the client of the API you've created to access that variable. However, if this code is executed in the browser, modern debugging tools can access this value while the debugger is in it's execution scope.

Further Reading

Alex
  • 34,899
  • 5
  • 77
  • 90
  • I would imagine debugging tools go via some API themselves. At least Mozilla has documented API, but it's Firefox-specific and it's not even obvious how to use it: https://developer.mozilla.org/en-US/docs/Tools/Debugger-API/Debugger – Vladimir Prus Jan 13 '15 at 19:19
0

You can't.

Although, you can see and edit it by debugging the script execution via console.

Alex M.
  • 635
  • 1
  • 6
  • 19