Home > database >  Calling a function within a function from outside [closed]
Calling a function within a function from outside [closed]

Time:10-07

I am having some trouble here trying to call function C from an onClick event on the page.

function leftArrowClicked() {
  functionA(functionC);
}

function functionA() {
  function functionB(w) {
    function functionC() {
      // do stuff
    };
  }
}
<div id="dashboard_left_arrow" onclick="leftArrowClicked()">Click</div>

But it's of course not working. Currently seeing 'functionC is not defined' in the console. I don't know much about nested functions, hence probably why my method isn't working. Any ideas?

CodePudding user response:

You can use something called Modular Design Patterns. It goes something like this -- you can see that functionA is an function that is already invoked, so I can call functionB directly on that because it is returned inside an object. Calling functionC can be done on top of that.

var functionA = (function() {
  function functionB(w) {
    function functionC() {
      // do stuff
      return 'inside functionC';
    }
    return {functionC:functionC};
  }
  return {functionB:functionB};
})();

function leftArrowClicked() {
  console.log(functionA.functionB('').functionC());
}
<div id="dashboard_left_arrow" onclick="leftArrowClicked()">Click</div>

  • Related