What's the difference between a closure calling an outer function directly and assigning a function to a variable and then calling it?

function fn1(){
  var a = 6;
  function fn2(){
    alert(a) ;
  }
  return fn2;
}
// var f = fn1();
// f()  alert 6
fn1() //

as in the above code, the variable f can be assigned to alert 6, but there is no response when calling fn1 directly. What is the principle of this, please?

Mar.07,2021

because return is a function
, fn1 () gets a function
fn1 () () calls the function


because you fn1 () only once.
and your f executes the function once during the assignment, and then f itself executes the function again, which is equivalent to twice.


if you take a closer look at fn1, direct fn1 has a result. The result is that the internal function fn2:

is returned.
var f = fn1(); // f  fn2
f() //  fn2() alert 6
//  alert 6 
fn1()()

you just call the function fn1 and return a function reference
execute fn1 () ()


fn1 () ()

when adding a ().
Menu