Closures and ES2015

前端 未结 1 1994
北荒
北荒 2021-01-14 10:17

I apologize in advance for yet another closure question, but I\'d like to clarify my understanding of the way closures are implemented in JavaScript.

Consider the fo

1条回答
  •  伪装坚强ぢ
    2021-01-14 10:40

    Does this sound about right?

    Pretty much. I just wouldn't use the work "copied", rather "linked". To simplify it a little:

    1. When a function is created, it stores are reference to the environment it was created it.
    2. When the function is executed, this stored environment becomes the "outer environment" of the newly created function environment.

    Or in pictures:

                      +----------------+                     +----------------+
       Function       |                |   [[Environment]]   |     Outer      |
       creation       |    Function    |-------------------->|  Environment   |
                      |                |                     |                |
                      +----------------+                     +----------------+
                                                                      ^        
                                                                      |        
                                                                      |        
                      +----------------+                              |        
       Function       |    Function    |  outer environment reference |        
       execution      |  Environment   |------------------------------+        
                      |                |                                       
                      +----------------+                                       
    

    This happens to every function and depending on your definition of closure1, this makes every function a closure (or not).


    1: I believe there are these two takes on what it means for a function to be a closure:

    • If a function stores a references to the environment it was created in, it's a closure (applies to every function in JS)
    • If a function stores a reference to the environment it was created in and "leaves" that environment (the environment "ceases to exist"), it's a closure. That's of course not always the case.

    0 讨论(0)
提交回复
热议问题