Organizational Research By

Surprising Reserch Topic

how to avoid global variables in javascript


how to avoid global variables in javascript  using -'javascript,global-variables'

We all know that global variables are anything but best practice. But there are several instances when it is difficult to code without them. What techniques do you use to avoid the use of global variables?

For example, given the following scenario, how would you not use a global variable?

JavaScript code:

var uploadCount = 0;

window.onload = function() {
    var frm = document.forms[0];

    frm.target = "postMe";
    frm.onsubmit = function() {
        startUpload();
        return false;
    }
}

function startUpload() {
    var fil = document.getElementById("FileUpload" + uploadCount);

    if (!fil || fil.value.length == 0) {
        alert("Finished!");
        document.forms[0].reset();
        return;
    }

    disableAllFileInputs();
    fil.disabled = false;
    alert("Uploading file " + uploadCount);
    document.forms[0].submit();
}


Relevant markup:

<iframe src="test.htm" name="postHere" id="postHere"
  onload="uploadCount++; if(uploadCount > 1) startUpload();"></iframe>

<!-- MUST use inline JavaScript here for onload event
     to fire after each form submission. -->


This code comes from a web form with multiple <input type="file">. It uploads the files one at a time to prevent huge requests. It does this by POSTing to the iframe, waiting for the response which fires the iframe onload, and then triggers the next submission.

You don't have to answer this example specifically, I am just providing it for reference to a situation in which I am unable to think of a way to avoid global variables.
    

asked Sep 16, 2015 by android_master
0 votes
2 views



Related Hot Questions

8 Answers

0 votes

The easiest way is to wrap your code in a closure and manually expose only those variables you need globally to the global scope:

(function() {
    // Your code here

    // Expose to global
    window['varName'] = varName;
})();

To address Crescent Fresh's comment: in order to remove global variables from the scenario entirely, the developer would need to change a number of things assumed in the question. It would look a lot more like this:

Javascript:

(function() {
    var addEvent = function(element, type, method) {
        if('addEventListener' in element) {
            element.addEventListener(type, method, false);
        } else if('attachEvent' in element) {
            element.attachEvent('on' + type, method);

        // If addEventListener and attachEvent are both unavailable,
        // use inline events. This should never happen.
        } else if('on' + type in element) {
            // If a previous inline event exists, preserve it. This isn't
            // tested, it may eat your baby
            var oldMethod = element['on' + type],
                newMethod = function(e) {
                    oldMethod(e);
                    newMethod(e);
                };
        } else {
            element['on' + type] = method;
        }
    },
        uploadCount = 0,
        startUpload = function() {
            var fil = document.getElementById("FileUpload" + uploadCount);

            if(!fil || fil.value.length == 0) {    
                alert("Finished!");
                document.forms[0].reset();
                return;
            }

            disableAllFileInputs();
            fil.disabled = false;
            alert("Uploading file " + uploadCount);
            document.forms[0].submit();
        };

    addEvent(window, 'load', function() {
        var frm = document.forms[0];

        frm.target = "postMe";
        addEvent(frm, 'submit', function() {
            startUpload();
            return false;
        });
    });

    var iframe = document.getElementById('postHere');
    addEvent(iframe, 'load', function() {
        uploadCount++;
        if(uploadCount > 1) {
            startUpload();
        }
    });

})();

HTML:


You don't need an inline event handler on the

However, if that's the case, then you should probably use an object literal or instantiated object and go about this in the normal OO way (where you can use the module pattern if it strikes your fancy).

answered Sep 16, 2015 by dahiyabecomp
0 votes

I suggest the module pattern.

YAHOO.myProject.myModule = function () {

    //"private" variables:
    var myPrivateVar = "I can be accessed only from within YAHOO.myProject.myModule.";

    //"private" method:
    var myPrivateMethod = function () {
    	YAHOO.log("I can be accessed only from within YAHOO.myProject.myModule");
    }

    return  {
    	myPublicProperty: "I'm accessible as YAHOO.myProject.myModule.myPublicProperty."
    	myPublicMethod: function () {
    		YAHOO.log("I'm accessible as YAHOO.myProject.myModule.myPublicMethod.");

    		//Within myProject, I can access "private" vars and methods:
    		YAHOO.log(myPrivateVar);
    		YAHOO.log(myPrivateMethod());

    		//The native scope of myPublicMethod is myProject; we can
    		//access public members using "this":
    		YAHOO.log(this.myPublicProperty);
    	}
    };

}(); // the parens here cause the anonymous function to execute and return
answered Sep 16, 2015 by girisha
0 votes
window.onload = function() {
  var frm = document.forms[0];
  frm.target = "postMe";
  frm.onsubmit = function() {
    frm.onsubmit = null;
    var uploader = new LazyFileUploader();
    uploader.startUpload();
    return false;
  }
}

function LazyFileUploader() {
    var uploadCount = 0;
    var total = 10;
    var prefix = "FileUpload";	
    var upload = function() {
    	var fil = document.getElementById(prefix + uploadCount);

    	if(!fil || fil.value.length == 0) {    
    		alert("Finished!");
    		document.forms[0].reset();
    		return;
    	 }

    	disableAllFileInputs();
    	fil.disabled = false;
    	alert("Uploading file " + uploadCount);
    	document.forms[0].submit();
    	uploadCount++;

    	if (uploadCount < total) {
    		setTimeout(function() {
    			upload();
    		}, 100); 
    	}
    }

    this.startUpload = function() {
    	setTimeout(function() {
    		upload();
    	}, 100);  
    } 		
}
answered Sep 16, 2015 by ajit.chavhan
0 votes

Sometimes it makes sense to have global variables in JavaScript. But don't leave them hanging directly off window like that.

Instead, create a single "namespace" object to contain your globals. For bonus points, put everything in there, including your methods.

answered Sep 16, 2015 by patilkiran.101
0 votes

Use closures. Something like this gives you a scope other than global.

(function() {
    // Your code here
    var var1;
    function f1() {
        if(var1){...}
    }

    window.var_name = something; //<- if you have to have global var
    window.glob_func = function(){...} //<- ...or global function
})();
answered Sep 16, 2015 by gauravg.gwl
0 votes

Some things are going to be in the global namespace -- namely, whatever function you're calling from your inline JavaScript code.

In general, the solution is to wrap everything in a closure:

(function() {
    var uploadCount = 0;
    function startupload() {  ...  }
    document.getElementById('postHere').onload = function() {
        uploadCount ++;
        if (uploadCount > 1) startUpload();
    };
})();

and avoid the inline handler.

answered Sep 16, 2015 by dhananjayksharma
0 votes

Using closures might be OK for small to medium projects. However, for big projects, you might want to split your code into modules and save them in different files.

Therefore I wrote jQuery Secret plugin to solve the problem.

In your case with this plugin the code would look something like the following.

JavaScript:

// Initialize uploadCount.
$.secret( 'in', 'uploadCount', 0 ).

// Store function disableAllFileInputs.
secret( 'in', 'disableAllFileInputs', function(){
  // Code for 'disable all file inputs' goes here.

// Store function startUpload
}).secret( 'in', 'startUpload', function(){
    // 'this' points to the private object in $.secret
    // where stores all the variables and functions
    // ex. uploadCount, disableAllFileInputs, startUpload.

    var fil = document.getElementById( 'FileUpload' + uploadCount);

    if(!fil || fil.value.length == 0) {
        alert( 'Finished!' );
        document.forms[0].reset();
        return;
    }

    // Use the stored disableAllFileInputs function
    // or you can use $.secret( 'call', 'disableAllFileInputs' );
    // it's the same thing.
    this.disableAllFileInputs();
    fil.disabled = false;

    // this.uploadCount is equal to $.secret( 'out', 'uploadCount' );
    alert( 'Uploading file ' + this.uploadCount );
    document.forms[0].submit();

// Store function iframeOnload
}).secret( 'in', 'iframeOnload', function(){
    this.uploadCount++;
    if( this.uploadCount > 1 ) this.startUpload();
});

window.onload = function() {
    var frm = document.forms[0];

    frm.target = "postMe";
    frm.onsubmit = function() {
        // Call out startUpload function onsubmit
        $.secret( 'call', 'startUpload' );
        return false;
    }
}

Relevant markup:


Open your Firebug, you will find no globals at all, not even the funciton :)

For full documentation, please see here.

For a demo page, please see this.

Source code on GitHub.

answered Sep 16, 2015 by akasati02

...