Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
105
rated 0 times [  107] [ 2]  / answers: 1 / hits: 32697  / 12 Years ago, thu, january 17, 2013, 12:00:00

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?


More From » scope

 Answers
37

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.


[#80814] Tuesday, January 15, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harleyaleenag

Total Points: 678
Total Questions: 121
Total Answers: 105

Location: Papua New Guinea
Member since Thu, Jul 9, 2020
4 Years ago
harleyaleenag questions
Thu, May 5, 22, 00:00, 2 Years ago
Wed, Aug 19, 20, 00:00, 4 Years ago
;