Dealing with JavaScript Scope

Over at Ajaxian, they've offered up a useful tip for dealing with code that exists in the global namespace and is conflicting with other scripts: move it into its own function. Example:

(function() {

// do you stuff here!

})();

What's the global namespace? That's the window object. Any time you instantiate a global variable, it is automatically part of the window object.

var myvar = 5;
alert(window.myvar); // alerts '5'

For more information on scope, be sure to check out my recent article on Digital Web on that very topic.

Published January 12, 2006 · Updated January 12, 2006
Categorized as JavaScript
Short URL: https://snook.ca/s/497

Conversation

1 Comment · RSS feed
Dustin Diaz said on January 12, 2006

That's what object notation is for. You nearly avoid all instances of other global properties.

Sorry, comments are closed for this post. If you have any further questions or comments, feel free to send them to me directly.

Want to learn about scaling CSS for large projects?

I'm available for full and half-day workshops on scalable CSS architecture. I can provide on-site training for your team. Interested?
Get in touch.