views:

73

answers:

3

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?

A: 

I would try

window["getNameField"] = function(fieldId) {
jhurshman
That will make precisely no difference.
Tim Down
+1  A: 

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

zem
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
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
A: 

You could instead call it as window.getNameField:

alert(window.getNameField().value);

Or you could define a vairable outside the closure:

var getNameField;

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

alert(getNameField().value);
Tim Down
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
Indeed you could. There's no serious problem with your code as it stands.
Tim Down