JavaScript - Declaring Global Scope for Nested Function?

前端 未结 5 1269
忘了有多久
忘了有多久 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 00:58

    There appear to be a couple of issues with your code

    1. The first line doesn't appear to be legal Javascript (JSLint agrees). To declare an uninitialized variable use the var B; syntax
    2. The code never calls A to initialize B so calling B() is invoking an uninitialized variable
    3. I'm fairly certain the code to initialize B inside of A is also not legal.

    Try the following

    var B; // Establish B as a global scope variable
    
    function A() {
      B = function() {
        alert('B is running');
      };
    }
    
    A(); // Call the function which will cause B to be initialized
    B(); // Run B
    

提交回复
热议问题