Passing parameters to JavaScript files

I’d recommend not using global variables if possible. Use a namespace and OOP to pass your arguments through to an object.

This code belongs in file.js:

var MYLIBRARY = MYLIBRARY || (function(){
    var _args = {}; // private

    return {
        init : function(Args) {
            _args = Args;
            // some other initialising
        },
        helloWorld : function() {
            alert('Hello World! -' + _args[0]);
        }
    };
}());

And in your html file:

<script type="text/javascript" src="https://stackoverflow.com/questions/2190801/file.js"></script>
<script type="text/javascript">
   MYLIBRARY.init(["somevalue", 1, "controlId"]);
   MYLIBRARY.helloWorld();
</script>

Leave a Comment