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?
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.