简体   繁体   中英

Calling function inside another function - uncaught error

I don't know if 'parameter' is the right term, but I'm trying to call a function inside another function and I'm getting the following error:

Uncaught ReferenceError: successMsg is not defined

I'm looping through a Trello board through their API which looks like this

var sportSuccess = function(successMsg) {
  console.log("sport");
    loopTrelloCards();
};

Trello.get('/lists/BOARDID/cards', sportSuccess, error);

And my loopTrelloCards function looks like

function loopTrelloCards() {
  for(i = 0; i < successMsg.length; i++) {
    var name = successMsg[i].name;
    var desc = successMsg[i].desc;
    var due = successMsg[i].due;
    var date = new Date(due);
    var day = addZeroToDate(date.getDate());
    var month = addZeroToDate(date.getMonth() + 1);
    var year = String(date.getFullYear());
    var eventDateShort = year + month + day;
    if (today < eventDateShort) {
      var year = year.substr(2);
      var eventDate = day + '.' + month + '.' + year;
      console.log(name + '  ' + desc + '  ' + eventDate);
    }
  }
}

When I place the code inside the function inside the sportsSuccess function it works, but when I call loopTrelloCards inside sportsSuccess it breaks.

Also, can you let me know if the term I used (parameter) is right? What would you call this?

Parameters in Javascript are local variables for the function' scope. So, as you are not passing successMsg as a parameter, is not accessible from the inner function.

Your options are:

  • Pass successMsg as a parameter to the inner function.
  • Define successMsg as a global variable (outside the functions) and access it there.
  • Not use the inner function and put the logic in the main function.

Quoting w3schools :

Function Arguments
Function arguments (parameters) work as local variables inside functions.

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