Friday, August 06, 2021

Closure Rules


Three rules for a closure to be created:


  • A function is defined within an outer function.
  • The outer function has variables and/or parameters (these will be on its stack frame).
  • A reference to the inner function is kept somewhere in the system.

It could be that the outer function returns a reference to the inner function that’s stored, or

It could be that the outer function passed a reference to the inner function to some other function which holds on to the reference (e.g. setTimer, addEventListener, etc…).


If no reference to the inner function is maintained, then a closure will not be formed and the stack frame of the outer function will be deallocated by the garbage collector.


Closures are useful because when the inner function does get executed, it’ll have access to the variables and parameters from the outer function’s stack frame.


function main(param) {
    // Parameters and local variables are on the stack frame of
    // function main
    
    // closures are for keeping a parameter or a variable alive after 
    // the function has returned.
   
    function interior() {
         console.log("interior function: ", param);
    }

    // this will return a reference to the function
    return interior;
}

// Creating two (2) closures
let f = main("hello");
f();

let g = main("hi");
g();


Image Credit: Andrea Rapuzzi, CC-BY-SA 3.0

Post a Comment

Note: Only a member of this blog may post a comment.