Calling a function out of scope
JavaScript Notes

Calling a function out of scope

Practical tips and subtle gotchas from real production experience.

With the advent of jQuery, coding in JavaScript became accessible to almost everybody. But with it came some very fundamental errors that could have been avoided if the person read the very basic of java script.

Users define a function inside a scope and tries to use it outside of it.

scriptfile-1.js
$(function () { // this is equivalent to $(document).ready(function() ...
    ...
    function makeBackgroundRed(){
        document.body.style.backgroundColor = "#F00"; // eww
    }
    ...
});

scriptfile-2.js 
$(function() {
    ...
    // make the background red
    makeBackgroundRed(); // error: makeBackgroundRed is not defined
});

This is very easy to fix. If makeBackgroundRed is going to be called in different places, might as well make it global. Define it in the global namespace. Or even better, stack all the methods that modify the document style in it's own namespace.

scriptfile-0.js
var Modifier = {
    makeBackgroundRed : function () {
        ...
    },
    makePageBounce : function () {
        ...
    }
    ...
};

Now from anywhere in your code you can run the DOM modifiers:

Modifier.makeBackgroundRed();

Did you like this article? Subscribe for more and follow updates via RSS.

Back to JavaScript articles

Join the Conversation

For my eyes only