Javascript 如何在javascript中定义一个新的全局函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3914483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:37:00  来源:igfitidea点击:

How to define a new global function in javascript

javascriptclosuresjslint

提问by Eric

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 windowcalled, getNameField.

当一个函数涉及到闭包时,我在尝试将它设为全局函数时遇到了一个问题。在下面列出的代码中,我有一个匿名方法,它在被window调用的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.comwith "Disallow undefined variables" turned on it gives me an error.

这在浏览器中效果很好,但是当我在JSLint.com 中运行代码并打开“禁止未定义的变量”时,它给了我一个错误。

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

第 17 行第 7 行的问题:getNameField未定义“ ”。

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

你能帮我解决这个问题,让 JSLint 实际上明白这个函数应该被认为是全局的吗?

回答by Tim Down

You could instead call it as window.getNameField:

您可以改为将其称为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);

回答by jhurshman

I would try

我会尝试

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

回答by zem

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

JSLint 为此需要注释注释。在此处阅读有关使用/*global */评论的信息。