简体   繁体   中英

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?

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

我会尝试

window["getNameField"] = function(fieldId) {

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM