SyntaxHighlighter JS

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>

No comments:

Post a Comment