Home  >  Q&A  >  body text

javascript - The issue about closures in js. I struggled with it last night and am almost dead now.

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~

迷茫迷茫2692 days ago620

reply all(6)I'll reply

  • 某草草

    某草草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

    reply
    0
  • 世界只因有你

    世界只因有你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

    reply
    0
  • 伊谢尔伦

    伊谢尔伦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

    reply
    0
  • 为情所困

    为情所困2017-06-05 11:15:08

    http://www.liaoxuefeng.com/wi...

    I suggest you read this

    reply
    0
  • 大家讲道理

    大家讲道理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.

    reply
    0
  • 世界只因有你

    世界只因有你2017-06-05 11:15:08

    console.log(console.log()) must be undefined, big brother

    reply
    0
  • Cancelreply