When actually is a closure created?

后端 未结 5 865
谎友^
谎友^ 2021-02-04 08:37

Is it true that a closure is created in the following cases for foo, but not for bar?

Case 1:



        
5条回答
  •  长发绾君心
    2021-02-04 09:18

    Actually, after several more years of JavaScript use and fairly thorough studies of it, I now have a better answer:

    Whenever a function comes into existence, then a closure is created.

    Because a function is just an object, we can more precisely say, whenever a Function object is instantiated (the function instance comes into existence), a closure is created.

    So,

    function foo() { }
    

    When the JS completes running the above line, there is a closure already, or

    var fn = function() { };
    

    Or

    return function() { return 1; };
    

    Why? Because a closure is just a function with a scope chain, so in every situation above, a function existed (it came into existence. You can call it (invoke it)). It also had a scope. So in my original question (I was the OP), every Case 1 to 4, there was a closure created, in every single case.

    Case 4 is an interesting case. After that code is run, there is a closure due to foo() coming into existence, but bar() doesn't exist yet (without the calling of foo()), so there was one closure created, not two.

提交回复
热议问题