Where does a JavaScript closure live?

前端 未结 5 866
攒了一身酷
攒了一身酷 2020-12-02 15:37

I wrote this code to teach myself about JavaScript closures:

function1 = function(){
  var variable = \"foo\"
  var function2 = function(argument){
    conso         


        
5条回答
  •  日久生厌
    2020-12-02 16:17

    For an explanation on how closures work see this answer.

    How do JavaScript closures work?

    At the virtual machine level, every function has its own lexical environment which keeps track of this information. The virtual machine finds which variables are accessed in closures and stores them on the heap, and they live for as long as any closure might need them.

    For more in-depth information see for example these two great pieces:

    • Grokking V8 closures for fun (and profit?)

    • How do JavaScript closures work under the hood

提交回复
热议问题