My attempts at giving global scope to a nested JavaScript function are not working:
//DECLARE FUNCTION B IN GLOBAL SCOPE
function B;
function A() {
//DEFINE FUNCTION B INSIDE NEST
B() {
alert("function B is running");
}
}
//CALL FUNCTION B FROM GLOBAL SCOPE
B();
This is just curiosity -- you are correct that I don't really have any good reason to want to do this.
TIA -- I don't have an SO account to respond to your answers...
What about:
There appear to be a couple of issues with your code
var B;
syntaxTry the following
You're close, but not completely correct.
These are the smallest amount of changes to your code to make it work as you asked:
function B;
will simply generate a syntax error.You can use a function expression. As functions are first class objects, you can assign a function to a variable:
You could also let
A
return a function:This would make the relation between
A
andB
a bit clearer.Of course you can always define a global variable by omitting
var
, but you should use this very carefully. Use as less global variables as possible.And I bet there is a better way of doing it, depending on what your actual goal is.
More about Functions and function scope.
You can do something like this:
It's a little icky to have a direct reference to "window", so you could do this (from the global context):