JavaScript - Declaring Global Scope for Nested Function?

前端 未结 5 1270
忘了有多久
忘了有多久 2021-02-14 00:36

My attempts at giving global scope to a nested JavaScript function are not working:

//DECLARE FUNCTION B IN GLOBAL SCOPE
function B;

function A() {

    //DEFIN         


        
5条回答
  •  甜味超标
    2021-02-14 01:16

    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.

提交回复
热议问题