Search code examples
javascriptclosuresjslint

How to define a new global function in javascript


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?


Solution

  • 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);