When actually is a closure created?

后端 未结 5 856
谎友^
谎友^ 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:09

    A closure is when free variables in some function code are bound to some values by the function "context" (closure being a more proper term here than context).

    
    

    Here, i is a free variable for the function code of foo. And this free variable is not bound to any particular value by any existing context (closure). So you don't have any closure.

    
    

    Now to create a closure you have to provide a value-bounding context:

    
    

    In summary, you can't have a closure unless a function returns another function. In that case, the returned function has all the variable-value bindings that existed in the returning function when it exited.

    
    

    Concerning your exemples:

    1. Case 1 is not a closure, it's just a function
    2. Case 2 is not a closure, it's another function with a free variable
    3. Case 3 is not a closure, it's yet another function with the special "variable" this. When the function is called as member of an object, the object is assigned to the value of this. Otherwise, the value of this is the global object.
    4. Case 4 is not a closure, it's a function defined inside another function. Should foo return bar, you would create a closure that contains only 'bar' and its value : function bar() {}.

提交回复
热议问题