《Eloquent JavaScript》第一版异常清理代码的变量重置逻辑问询
Understanding the State Restoration Logic in This Code
Let’s start by restating the code for clarity:
var currentThing = null; function processThing(thing) { var prevThing = currentThing; currentThing = thing; /* do complicated processing... */ currentThing = prevThing; }
What’s the logic behind currentThing = prevThing at the end?
This line exists to restore the shared currentThing variable to its original state before the function ran. Here’s the full flow to put it in context:
- First, we take a "snapshot" of
currentThing’s value before we start processing the newthing, storing it inprevThing. - We update
currentThingto the incomingthing—this makes the current item available to any code that relies on this shared variable during the complex processing step. - Once processing finishes (successfully or, with proper error handling, even if it fails), we reset
currentThingback to the snapshot value we saved.
Why does this pattern matter?
This is a defensive programming technique to avoid unintended side effects with shared state:
currentThingis a shared variable (likely global or module-scoped) that other parts of your code might depend on. If we skipped resetting it, afterprocessThingruns,currentThingwould stay set to the last processed item. This could break other functions that expect it to benull(or its previous value).- Tied directly to the "Cleaning up after Exceptions" section: This pattern is designed to work with
try/finallyblocks. If the complex processing throws an error, wrapping that code in atryand putting thecurrentThing = prevThingline in afinallyguarantees the shared state is always restored—even when exceptions occur. This prevents your application from getting stuck in an inconsistent state after a failure.
In short, this ensures that calling processThing doesn’t leave lasting, unexpected changes to shared state that could break other parts of your program.
内容的提问来源于stack exchange,提问作者Osi
相关产品推荐
相关产品推荐

