简体   繁体   中英

Global variables in Javascript (jQuery)

So this is the first time I am using Javascript in a much more powerful context, having a thick client and doing much of the heavy-lifting through javascript in itself. I am using jQuery, and a lot of the code is getting muddy at the moment coz it's all just a bunch of functions.

Turns out for some of my functions, I required variables to be passed through multiple functions with their value being maintained. The obvious way of doing this is by declaring them outside of the scope of the function and then have the function manipulate it the way it ought to . (These variables are objects and not primitive type, so I guess javascript being pass by reference, this works).

For instance, I probably have something like this

var node = //init with some value;

$(document).ready(setup);
function setup()
{
 A();
 B();
}

function A()
{
  // operate on var node
}

function B()
{
  // operate on var node
}

This is obviously a scaled down version of my code, but captures the way I deal with global variables. My question is, is there a more elegant way to do the above ?

Thanks

Any reason why you can't do:

$(document).ready(function() {
    var node = //init with some value;
    setup(node);

    function setup(node) {
        A(node);
        B(node);
    }

    function A(node) {
      // operate on var node
    }

    function B(node) {
      // operate on var node
    }
});

In general, using global variables and functions is a bad idea and should be avoided wherever possible.

Note that while you appear to have been asking specifically about node , your functions setup , A and B are also all global variables in your version.

The simplest approach would be to put all these declarations inside an anonymous function:

$(document).ready(function() {

    var node = ...;

    function A() {
        ...
    }

    function B() {
        ...
    }

    function setup() {
        A();
        B();
    }

    setup();
});

Only use one global variable (or as few as possible). Make any functions or objects members of your one global variable.

Douglas Crockford says

An objective measure of the quality of a JavaScript program is How many global variables and global functions does it have? A large number is bad because the chance of bad interactions with other programs goes up. Ideally, an application, library, component, or widget defines only a single global variable. That variable should be an object which contains and is the root namespace for all of your stuff.

Yahoo's single global is YAHOO. It is spelled in all caps to identify it as something special, since all lower case is ordinary and initial caps indicates a constructor. Being in all caps, it is unlikely that someone would use it accidentally, which further reduces the likelihood of collision.

http://www.yuiblog.com/blog/2006/06/01/global-domination/

Also, you can create objects to further organize your code.

GLOBAL.myObject = {}; GLOBAL.myObject.myFunction = ...

I prefer the "revealing module" pattern :

var myApp = (function () {
    // privates
    var node;

    var a = function () {
        // operate on node
    };

    var b = function () {
        // operate on node
    };

    // publics
    var init = function () {
        // initialization stuff
        a();
        b();
    };

    return {
        init: init
    };
})();

$(document).ready(function () {
    myApp.init();
});

This way you only ever have one global, myApp , which stores everything else your app needs.

I think it makes the code harder to understand, I'd much rather take the variable in as an argument and have it as a return.

$(function(){
    var outcome = multiply(add(5));
});

function add(num)
{
    return num+1;
}

function multiply(num)
{
    return num*5;
}

If you feel like you absolutely want to have global variables wrap your stuff in a closure so it doesn't actually go to a global scope.

ie,

(function(){
    var a; // can be used in any functions within this closure, but not polluting window
    function A()
    {
        a = 'blah';
    }
})();

There are many. For instance, objects.

// jQuery shorthand for "wait till DOM ready"
$( function() {
   // create node object
   var node = {
      id: /* some value */,
      setup: function() {
         this.A();
         this.B();
      },
      A: function() {
         // operate on this.id
      },
      B: function() {
         // operate on this.id
      }
   };
   // setup node object
   node.setup();
} );

Global variables are trouble waiting to happen. Don't dirty up your global namespace. Javascript is an object oriented language, use objects. Notice your object can have a property that you can reference with the this keyword from within the objects methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM