15

I have an issue trying to make a function global when it is involved in closure. In the code listed below I have an anonymous method which defines at new function on the window called, getNameField.

(function () {
    function alertError (msg) {
        alert(msg);
    }
    window.getNameField = function (fieldId) {
        try{
            if(!fieldId) {
                fieldId='name';
            }
            return document.getElementById(fieldId);
        } catch(e) {
            alertError(e);
        }
    };
}());

alert(getNameField().value);

This works great in the browser, but when I run the code in JSLint.com with "Disallow undefined variables" turned on it gives me an error.

Problem at line 17 character 7: 'getNameField' is not defined.

Can you help me fix this so that JSLint actually understands that this function should be considered global?

Eric
  • 6,563
  • 5
  • 42
  • 66

3 Answers3

21

You could instead call it as window.getNameField:

alert(window.getNameField().value);

Or you could define a variable outside the closure:

var getNameField;

(function(){
    getNameField=function(fieldId){
        // Code here...
    };
}());

alert(getNameField().value);
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Along the same lines I could create a variable that acts as a "namespace", where the variable is an associative array and the function is assigned to one of the entries in the associative array. The downside, though minor, is that I would have to redesign all of my code to use the "namespace" variable if I wanted to stay consistent. – Eric Oct 12 '10 at 16:36
  • 1
    Indeed you could. There's no serious problem with your code as it stands. – Tim Down Oct 12 '10 at 17:15
10

I would try

window["getNameField"] = function(fieldId) {
jhurshman
  • 5,861
  • 2
  • 26
  • 16
2

JSLint takes annotating comments for this purpose. Read up here on using a /*global */ comment.

zem
  • 1,257
  • 9
  • 15
  • Generally in the JS code I want to avoid using comments because of the extra characters that are downloaded to the browser. I could continually add and remove the comments but I don't like that manual step either. – Eric Oct 12 '10 at 17:31
  • 4
    yes, the file is smaller if you remove all comments. it's also smaller if you run it through a javascript minimizer, which does that and shortens all variable names and removes all unnecessary whitespace. in either case, you don't want to develop using the "minified" version. either take the insignificant size difference from source comments, or make a minified copy when you "deploy." – zem Oct 12 '10 at 21:53