Article From:https://segmentfault.com/q/1010000012146822
function f1(){
    var n=999;
    function f2(){
    return f2;
  var result=f1();
  result(); // 999

I would like to ask why this code does not add (return) F2, I tried, and (finally) will prompt result is not defined and wrong. Xiao Bai asked what was in it. What’s the difference between returning F2 and returning F2 ()?

Answer 0:

First answer:

  • The function name returns a function body

  • The function name plus parenthesis returns the return value generated by calling this function.

So when you don’t add parentheses. The function of F1 to return to F2 is

function f2(n){

This thing.
Then the following code var result = F1 () is equivalent to giving this function the result of the function (that is, the return value return of the function) to result (the body of F2), when result is aFunction name。Then, after parentheses are called, the function will execute the function, so result () actually executes the code in the function above.

If you add brackets, F1 return is F2 (), that is, the return value of F2, because the F2 function body does not write return, so it returns undefined. So result = = = = undefined, not a function.So the return () call to it will be wrong.

You can understand that parenthesis is to perform the function body represented by the function name.

No parentheses represent the body of a function.

Answer 1:

()It is the execution.
return f2;Return to the F2 method
return f2();Return the results of the F2 execution

Answer 2:

return f2 It’s going back to the literal function of the function
Parenthesis is executed, and the result is calculated before assignment.

You can try it in console:

function f() {
    return 1

console.log(f)    // => ƒ f() {
                  //          return 1
                  //    }
console.log(f())  // => 1

Answer 3:

return f2: f2It’s a variable,
var f2 = function(){

// Return will default to return undefined without writing


return f2(): f2The function is called first, and because it does not write return, it will return to undefined.

Leave a Reply

Your email address will not be published. Required fields are marked *