How can I call the returned inner function of another function?

I am trying to solve a problem from an online tutorial. Consider the following function:

var badFunction = function() {
  return function() {
    return "veryBad"
  }
}

This badFunctionreturns a function that returns "veryBad". I want to keep "veryBad"inside theBad. How can I call a return internal function? This answer is not acceptable:

var theBad = "veryBad!";

And this is not so:

var theBad = badFunction(); 
theBad();

Although both of these work. So what can I call an internal function?

+4
source share
1 answer

Just call the return value:

var theBad = badFunction()();

First, call the function badFunction, after the function finishes, it will call the returned function. The score looks something like this:

badFunction()();
^^^^^^^^^^^^^
Step 1, calls badFunction

, badFunction, :

(function() { // <-- This is the return value of badFunction
  return "veryBad"
})();
  ^^
  Step 2, call the returned function expression for "veryBad"

, , :

var veryBadFunc = badFunction();
var theBad = veryBadFunc();

veryBadFunc, , theBad. , . , - , .

+10

Source: https://habr.com/ru/post/1684577/


All Articles