Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: access variables inside anonymous function from the outside

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?

like image 246
steve Avatar asked Jan 17 '13 06:01

steve


People also ask

Can we access variable outside function in JavaScript?

Variables declared Globally (outside any function) have Global Scope. Global variables can be accessed from anywhere in a JavaScript program. Variables declared with var , let and const are quite similar when declared outside a block.

How do you access a variable outside a function?

1 Answer. Using the keyword "global", you can change the scope of a variable from local to global, and then you can access it outside the function.

Can you pass parameters to anonymous function JavaScript?

The syntax is simple: you can simply declare the anonymous function and make it execute by just calling it using the parenthesis at the end of the function. You can simply pass the parameters inside the immediate execution of the anonymous function as we have seen in the above example.


3 Answers

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.

like image 150
Faiz Avatar answered Nov 02 '22 07:11

Faiz


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

like image 20
SangYeob Bono Yu Avatar answered Nov 02 '22 05:11

SangYeob Bono Yu


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

like image 23
Eevee Avatar answered Nov 02 '22 05:11

Eevee