Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent 'global' references in javascript

Tags:

javascript

I've got a problem of having code variable names conflicting each other, ie;

<script type="text/javascript">var a = "hello"; </script>
<script type="text/javascript">alert(a);//this works, when I want 'a' not to exist </script>

Are closures the only option?

Coming from a c# background, its like constructing an unreferenced instance of a delegate, then calling it inline, which seems a bit messy

(function(){var a = "hello";})();
(function(){alert(a);})();//yes! working as expected
like image 771
maxp Avatar asked Dec 13 '22 01:12

maxp


1 Answers

Using a (immediately self-executing) function to create a new scope is indeed the way to go.

This also has the advantage that you can ensure that certain variables have certain values. When using jQuery, the following is common for example:

(function($, window, undefined) {
    // ...
})(jQuery, this);

Unless you have tons of functions with only a single statement in each (like in your example) it is also perfectly readable.

like image 184
ThiefMaster Avatar answered Dec 20 '22 12:12

ThiefMaster