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?
Global functions are custom functions that can be called from custom actions configured for request, change, or custom schedules, whenever necessary.
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.
The syntax for creating a function: let func = new Function ([arg1, arg2, ... argN], functionBody); The function is created with the arguments arg1...
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With