Every tutorial that I've seen describes that to create a global variable you have to declare it outside the function.
var myvar = 5; function myFunction() alert(myvar); // 5 }
And this is the way I've been doing it for years. The problem is, I've never been particularly happy about this. It never felt self contained. Then I thought, "Hey, why not just attach it to the window object?" I almost feel like an idiot for not having thought of this sooner and I suspect you JavaScripters out there are thinking "well, duh".
function setValue() { window.myValue = "test"; } function getValue() { alert(window.myValue); // "test" (assuming setValue has run) }
A quick search via Google revealed just how "in the dark" I've been. It turns out that when a global variable is set, it's added to the window object!
var myValue; function setValue() { myValue = "test"; } function getValue() { alert(window.myValue); // yup, it's "test" } Source: http://snook.ca/archives/javascript/global_variable/
No comments:
Post a Comment
Post your comments here: