简体   繁体   中英

variable function undefined error

i have this two functions, inside one function.

var funcA = function(){
  var funcB = function(){
    // function codes
    funcC();
  }

  var funcC = function(){
    // function codes
    funcB();
  }
}

funcA is executed first, then when I call funcB it produce error Object [object global] has no method 'funcC' . if i put funcC right before funcB the error is now pointing to undefined funcB .

how to fix this problem?

Your problem is in the way you're declaring functions:

var funcB = function(){
    // function codes
    funcC();
  }

var funcC = function(){
    // function codes
    funcB();
}

When you're declaring funcB , it tries to find funcC , which doesn't exist, yet. This breaks your code, throwing an undefined error.

You can define the functions like this:

function funcB(){
    // function codes
    funcC();
  }

function funcC(){
    // function codes
    funcB();
}

However, if funcB calls funcC , and funcC calls funcB , it doesn't matter how they're declared / initialized, you're going to have an infinite loop, probably resulting in a stack overflow-like error, or a crashing browser (/tab).

Chrome throws this:

RangeError: Maximum call stack size exceeded

To avoid that error, do something like this:

function funcB(calledFromC){
    if(!calledFromC){
        funcC(true);
    }
}

function funcC(calledFromB){
    if(!calledFromB){
        funcB(true);
    }
}

Or shorter:

function funcC(calledFromB){
    !calledFromB && funcB(true);
}

If you would declare functions like this:

var funcA = function(){
   function funcB() {
      funcC();
   }

   function funcC {
      funcB();
   }
}

it would work. Why you ask? Read more about hoisting, scoping, function declarations and function expression here

check fiddle here

of-course it would be an infinite loop, so don't do this, but it would be correct javascript.

edit: if you would like to call them out of the scope (outside of funcA), you need to return them:

 var funcA = (function() {
    var funcB = function () {
        //code here
    };
    var funcC = function () {
        //code here
    };
    return {
        funcB: funcB,
        funcC: funcC
    };
   })();

Now you can do this outside the funcA:

funcA.funcB();
funcA.funcC();

You are probably asking the wrong question as interlinked methods rarely end happily.

The answer to your question really is because of this earlier answer regarding when functions actually exist . In particular read about function hoisting.

var funcA = function() {

  function funcB(){
    // function codes
    funcC();
  }

  function funcC() {
    // function codes
    funcB();
  }
}

funcA.funcB();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM