Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Declaring Global Scope for Nested Function?

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...

like image 531
nestor Avatar asked Mar 04 '11 19:03

nestor


1 Answers

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:

var B; // declare (global) variable (outer scope)

function A() {
    // assign a function to it
    B = function() {
        alert("function B is running");
    };
}

// we have to call A otherwise it won't work anyway
A();
// call B
B();

You could also let A return a function:

function A() {
    return function() {
        alert("function B is running");
    };
}

B = A();

This would make the relation between A and B 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.

function A() {
    B = function() {
        alert("function B is running");
    };
}

And I bet there is a better way of doing it, depending on what your actual goal is.


More about Functions and function scope.

like image 123
Felix Kling Avatar answered Oct 11 '22 04:10

Felix Kling