[removed] access variables inside anonymous functi

2019-01-26 05:23发布

Say I have this anonymous function:

(function(window){

 var private = 'private msg';

 function sayit() {
   alert(private) // works
 }

 document.body.onclick = sayit; // works

})(window);

// private shouldn't be accessible here

Is this how JavaScript should behave?

That is, there is no way to access private from anywhere outside of that anonymous function?

If so, is it possible to find some kind of hack to access private from the outside, leaving the code the way it is?

5条回答
ゆ 、 Hurt°
2楼-- · 2019-01-26 05:50

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

查看更多
老娘就宠你
3楼-- · 2019-01-26 05:50

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'
查看更多
叛逆
4楼-- · 2019-01-26 05:56

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

查看更多
迷人小祖宗
5楼-- · 2019-01-26 06:02

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.

查看更多
Emotional °昔
6楼-- · 2019-01-26 06:02

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... :)

查看更多
登录 后发表回答