简体   繁体   中英

Accessing JavaScript closure from outside

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.

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

You can't.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM