JavaScript - Declaring Global Scope for Nested Function?

前端 未结 5 1272
忘了有多久
忘了有多久 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:03

    You're close, but not completely correct.

    1. You have to define B as a variable and then assign a function to it.
    2. Also run A() before executing B, otherwise B will be undefined. The easiest way of running it is the way that I show in my code example.

    These are the smallest amount of changes to your code to make it work as you asked:

    var B;
    
    (function A() {
        // define function B
        B = function() {
            alert("function B is running");
        }
    })();
    
    // call function B globally
    B();
    

提交回复
热议问题