3

I have an external JavaScript file that will be used on pages with lots of other scripts. My script involves a lot of jQuery that listens for events, and by design, I have many global vars declared. I've been reading best practice articles, and a lot is said about 'polluting the global namespace' and inadvertent script interaction.

What's the best way to enclose (encapsulate?) my JavaScript file so that:

  • I can still access some of the variables outside of the enclosure
  • The jQuery event listeners will function properly

I'm not at liberty to disclose the code, so even general responses are appreciated. Additionally, any other tips on making scripts less vulnerable to other scripts on the page are welcome.

I've found enclosure styles for regular JavaScript, but does the use of jQuery complicate this?

6 Answers6

1

One method is to namespace like this:

var MyNamespace = {
    doSomething: function() {},
    reactToEvent: function() {},
    counter: 0
}

You will just have to refer to the functions or variable using the namespace: MyNamespace.reactToEvent. This works fine for separating what you would normally have in the window (where all the confrontation is).

natedavisolds
  • 4,305
  • 1
  • 20
  • 25
1

You can wrap your code in an anonymous Javascript function and only return what you want to expose to the outside world. You will need to prefix var to your global variables so that they remain only in the scope of the anonymous function. Something like this:

var myStuff = (function() {

   var globalVar1;
   var globalVar2;
   var privateVar1;

   function myFunction() {
     ...
   }

   function myPrivateFunction() {
     ...
   }

   return {
      var1: globalVar1,
      var2: globalVar2,
      myFunction: myFunction
   };

})();

Now you can access myStuff.var1 and myStuff.myFunction().

Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
1

Generally what this boils down to is encapsulating your objects into a "namespace". I use quotes there because the term is not an official semantic in JavaScript, but rather one that is achieved through basic object encapsulation.

There are several ways to do this, and it ultimately comes down to personal preference.

One approach is to just use a basic JS object, and keep everything in it. The name of the object should be semantic and give the object some meaning, but otherwise it's purpose is to just wrap your own code and keep it out of the global namespace.

var SomeName = {
    alpha: 1,
    beta: {a: 1, b: 2},
    gamma: function(){ 
        SomeName.alpha += 1;
    }
}

In this case, only SomeName is in the global namespace. The one downside to this approach is that everything inside the namespace is public, and you have to use the full namespace to reference an object, instead of using 'this' - e.g. in SomeName.gamma we have to use SomeName.alpha to reference the contents of alpha.

Another approach is to make your namespace a function with properties. The nice feature of this approach is you can create 'private' variable through closures. It also gives you access to closured functions and variables without full namespace referencing.

var SomeName = (function(){
   var self = this;
   var privateVar = 1;
   var privateFunc = function() { };   

   this.publicVar = 2;
   this.publicFunc = function(){
       console.log(privateVar);
       console.log(this.publicVar); // if called via SomeName.publicFunc

       setTimeout(function(){ 
           console.log(self.publicVar);
           console.log(privateVar);
       }, 1000);
   };
}();

The other bonus of this approach is it lets you protect the global variables you want to use. For example, if you use jQuery, AND another library that creates a $ variable, you can always insure you are referencing jQuery when using $ by this approach:

var SomeName = (function($){
    console.log($('div'));
})(jQuery);
Matt
  • 41,216
  • 30
  • 109
  • 147
0

Two ways to encapsulate or limit namespace pollution

1) Create one global var and stuff everything you need into it.

var g = {};
g.somevar = "val";
g.someothervar = "val2";
g.method1 = function() 
{
   // muck with somevar
   g.somevar = "something else";
};

2) For inline scripts, consider limiting the scope of the functions called.

<script>
(  
   function(window)
   {
      // do stuff with g.somevar
      if(g.somevar=="secret base")
        g.docrazystuff();      

   }
)();  // call function(window) then allow function(window) to be GC'd as it's out of scope now
</script>
mrk
  • 4,999
  • 3
  • 27
  • 42
0

I just started using RequireJS and have now become obsessed with it.

It's basically a dependency management system in a modular JavaScript format. By doing so you can virtually eliminate attaching anything to the global namespace.

What's nice is that you only reference one script on your page require.js then tell it what script to run first. From there it is all magic...

Here's an example implementation script:

require([
   //dependencies
   'lib/jquery-1.6.1'
], function($) {
   //You'll get access to jQuery locally rather than globally via $


});

Read through the RequireJS API and see if this is right for you. I'm writing all my scripts like this now. It's great because at the top of each script you know exactly what you dependencies are similar to server-side languages - Java or C#.

John Strickler
  • 25,151
  • 4
  • 52
  • 68
  • Hmm I'm very interested in this. In your experience, how much modifications to pages (perhaps with a few separate external script files, a few inline scripts) are necessary to get this to work? Was it easy? –  Jun 10 '11 at 15:37
  • @chris Adopting it wasn't so bad, the external script files all use the `define()` function to register them as modules. Then your implementation page just references those modules you've defined. I'm going to write a blog post about it probably in the next week or so. I'll be sure to post back here with a link. – John Strickler Jun 10 '11 at 16:34
0

This is a common practice with jQuery plugins for the same reasons you mention:

;(function ($) {

    /* ... your code comes here ... */

})(jQuery);

This is an immediate function. If you declare your "global" variables inside, they will be local to this closure (still "global" for the code you create inside). Your event listeners will work inside here too, and you will still be able to reach real global variables.

aorcsik
  • 15,271
  • 5
  • 39
  • 49