Returning a Function with Captured Data
A returned function can use values from the lexical environment in which it was created, including after the creating call finishes.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Build a concrete multiplier
Calling a factory with factor three can return a function that multiplies each supplied number by three. A call on four then yields twelve. An independently created multiplier with factor five yields twenty. This is an application of lexical closures.
Check retained mutable data
A returned function reading a captured list may see later mutations to that same list. If it promises a stable preset, store the immutable values needed at the time of construction. Object identity helps locate what remains shared.[1][2]
Trace two closures created by separate calls
Calling make_threshold(10) can return a function that accepts a value when it reaches ten. A second factory call with twenty produces an independent check. Sending fifteen to each should yield true and false respectively. This tests the captured threshold even though both returned objects implement identical code. A factory can capture the threshold directly when it remains immutable. See binding a name to a value.
Decide when the state is read
Suppose a factory receives a dictionary of thresholds and the caller later changes the limit from ten to twenty. A returned check can read the dictionary each time or store a snapshot of the numeric limit at construction. A check for fifteen after the update distinguishes the behaviors. A shallow container copy may still share mutable settings under nested keys, so define the depth the result promises to freeze. See shallow container copies.