2013-02-22

Eliminate JavaScript global variables

Global variables in JavaScript can be overwritten, resulting in bugs. For example,

<html><head>
<script>
var counter = 0;

function increaseCounter() {
    ++counter;
    alert("Counter is " + counter);
}
</script>

<script>
var counter="A";
</script>
</head><body><form>
    <input type="button" value="Increase Counter" onclick="increaseCounter();" />
</form></body></html>

will output "Counter is NaN" when the button is clicked.

Global variables in JavaScript can be eliminated by closures. For example the previous JavaScript can be refactored as,

<html><head>
<script>
var CounterJS = (function() {
    var counter = 0;

    return {
        increaseCounter: function() {
            ++counter;
            alert("Counter is " + counter);
        }
    }    
}());
</script>

<script>
var counter="A";
</script>
</head><body><form>
    <input type="button" value="Increase Counter" onclick="CounterJS.increaseCounter();" />
</form></body></html>

3 comments:

  1. Every visit leaves a positive impression because dualmonitortools.net consistently delivers reliable performance and valuable monitor management features. The platform is intuitive, responsive, and an excellent choice for anyone looking to optimize their multi-monitor workspace with minimal effort.

    ReplyDelete
  2. Brilliant experience from my very first visit xpsviewer.net thanks to its smooth document viewing capabilities. Everything works flawlessly, the interface is user-friendly, and the platform makes opening XPS files simple, efficient, and completely stress-free for everyone.

    ReplyDelete
  3. Could not be happier after trying this platform filecorrupter.io for software testing needs. Everything functions perfectly, navigation feels effortless, and generating corrupted files has become much faster, allowing developers to complete validation tasks with greater confidence and efficiency.

    ReplyDelete