Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 794
Eric Avatar asked Oct 12 '10 12:10

Eric


People also ask

How do you define a global function?

Global functions are custom functions that can be called from custom actions configured for request, change, or custom schedules, whenever necessary.

How do you make a global function?

The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.

How do you create a new function in JavaScript?

The syntax for creating a function: let func = new Function ([arg1, arg2, ... argN], functionBody); The function is created with the arguments arg1...

How do you declare a global object in JavaScript?

A global object is an object that always exists in the global scope. In JavaScript, there's always a global object defined. In a web browser, when scripts create global variables defined with the var keyword, they're created as members of the global object. (In Node.


1 Answers

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);
like image 98
Tim Down Avatar answered Sep 20 '22 15:09

Tim Down