Categories
Web Development

JavaScript Globals

JavaScript, always mistaken to be an easy langauge, throws awrench when you need to get a global variable (ugh!). The solution is really easy, though.

Share

If you ever wrote mildly substantial JavaScript, you noticed that that JavaScript is not as premiscuous as it may appear when it comes to namespaces.
If you define a variable outside any block of code, that variable is not necessarily available within the body of functions, say.
The solution is to use the a real global element and ‘attach’ it the global value as property. The object of choice is window and the solution is as simple as
window.myProperty="Yuval";
Thereafter the global value is accessible as
window.myProperty

Very elementary, but I always forget these facts…

Share
Share