如何在 JavaScript 中定义新的全局函数
当函数涉及闭包时,我在尝试将函数设为全局时遇到问题。在下面列出的代码中,我有一个匿名方法,它在 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);
这在浏览器中效果很好,但是当我在打开“禁止未定义的变量”的情况下在 JSLint.com 中运行代码时,它会给出我一个错误。
第 17 行第 7 行字符出现问题: 未定义“
getNameField
”。
你能帮我解决这个问题,以便 JSLint 真正理解这个函数应该被视为全局函数吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将其称为
window.getNameField
:或者您可以在闭包外部定义一个变量:
You could instead call it as
window.getNameField
:Or you could define a variable outside the closure:
我会尝试
I would try
JSLint 为此目的采用注释。请阅读此处了解如何使用
/*global */
注释。JSLint takes annotating comments for this purpose. Read up here on using a
/*global */
comment.