Because I just started learning about closures, I didn’t understand many things. How do you get undefined
in the console as shown in the picture? I only executed the return function, why are there two execution results? Guys please explain in detail~
某草草2017-06-05 11:15:08
You can repeat the following two pieces of code. var result = f1();
The variable points to the function console.log(result())
In fact, it can be converted to f1()()
That is The function returned by f1()
is f2()
, so the f2()
function under f1()
will be executed first, and then f1()
, so first console.log(n )
That is, 1
return f2
when executing function f1()
, but since the function does not return a value, it prints out undefined
世界只因有你2017-06-05 11:15:08
Essentially
var n = 1;
function f2() {
console.log(n);
}
console.log(f2())
Because your f2 does not return a value, so it is undefined
伊谢尔伦2017-06-05 11:15:08
console.log(result())
First output 1, because result() calls f2()
Then output is undefined, because result() has no return value
大家讲道理2017-06-05 11:15:08
First result=f1(); At this time, result=f2;
Then console.log(result()); First execute result, which is f2, and print the value of n. Because you did not execute test, n is 1, so what is printed is 1 Then execute console.log(result()); because result() has no return value, it is undefined.