JavaScript: access variables inside anonymous function from the outside

。_饼干妹妹 提交于 2019-11-29 09:14:24

Yes, this is how Javascript lets you have 'private' variables (hidden in a function scope).

No, there's no hack available to access variables such as private without re-writing the code.

Variables defined with var within a function can be accessed only from within that function.

Ok. I got it.

(function(window){
    var alert_original = window.alert;
    window.alert = function(data) {
        window.extracted = data;
        alert_original(data);
    };
})(window);

(function(window){
    var private = 'private msg';
    function sayit() {
    alert(private) // works
 }
 document.body.onclick = sayit; // works
})(window);

After you click body, you can get 'private msg' from extracted

They aren't intended as "private" variables; that's just how closures work. You can do the same thing in Perl and Python, at the very least, and probably a great many other languages with closures and lexical scoping.

Debuggers like Firebug or Chrome Inspector can still show you the entire stack at any point (including closed-over variables), but other than that and without changing the original code, I think you're out of luck.

Perhaps if you told us your actual problem... :)

That's the whole point of having scope and private variables

Either

Set the private value to a global variable?

or

declare the variable outside

You would have to do something like this:

var Test = (function(window){
 var private = 'private msg';
 var api = {};

 function sayit(){
   alert(private) // works
 }
 document.body.onclick = sayit; // works

api.sayit = sayit;
return api;
})(window);

Test.sayit(); //this would alert 'private msg'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!