简体   繁体   English

从外部访问JavaScript闭包

[英]Accessing JavaScript closure from outside

I have an JavaScript library that implements "private fields" with closures, along the lines of: 我有一个JavaScript库,它实现了带有闭包的“私有字段”,大致如下:

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. Chrome devtool当然可以,但是我看不到以编程方式实现它的方法,在Object或Function中都没有做到这一点。

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. 您创建的API的客户端无法访问该变量。 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. 虽然,您可以通过控制台调试脚本执行来查看和编辑它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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