Close external jQuery script

I have an external JavaScript file that will be used on pages with a lot of other scripts. My script includes a lot of jQuery that listens for events, and by design I have announced many global wars. I read articles on best practice, and a lot is said about the “pollution of the global namespace” and the unintended interaction of the script.

What is the best way to enclose (encapsulate?) My JavaScript file so that:

  • I can access some of the variables outside the shell
  • JQuery event listeners will function correctly

I have no right to disclose the code, so even general answers are evaluated. In addition, any other tips for creating scripts that are less vulnerable to other scripts on the page are welcome.

I found shell styles for regular JavaScript, but does jQuery use this?

+3
source share
6 answers

This usually comes down to encapsulating your objects in a "namespace". I use quotes there because the term is not official semantics in JavaScript, but rather what is achieved by encapsulating the underlying object.

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

One approach is to simply use the underlying JS object and store everything in it. The name of the object should be semantic and give the object some meaning, but otherwise its purpose is simply to wrap your own code and not allow it from the global namespace.

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

. , , , 'this' - . SomeName.gamma SomeName.alpha .

- . 'private' . .

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);
   };
}();

- , . , jQuery, , $, , jQuery $ :

var SomeName = (function($){
    console.log($('div'));
})(jQuery);
+1

- , :

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

: MyNamespace.reactToEvent. , window ( ).

+1

Javascript , . var , . - :

var myStuff = (function() {

   var globalVar1;
   var globalVar2;
   var privateVar1;

   function myFunction() {
     ...
   }

   function myPrivateFunction() {
     ...
   }

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

})();

myStuff.var1 myStuff.myFunction().

+1

1) var , .

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

2) .

<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 out of scope now
</script>
0

RequireJS .

JavaScript. , .

, script require.js, , script. ...

script:

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


});

API RequireJS , . . , script , - Java #.

0
source

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 for this closure (still “global” for the code that you create inside). Your event listeners will also work internally, and you can still achieve real global variables.

0
source

All Articles