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 ().
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-34590c2-1848e.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-34590c2-1848e.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?