I don't understand what is being passed into the function withBoxUnlocked
. It must be referring to get content()
, but body is not a keyword, nor is it the name of the getter.
const box = {
locked: true,
unlock() { this.locked = false; },
lock() { this.locked = true; },
_content: [],
get content() {
if (this.locked) throw new Error("Locked!");
return this._content;
}
};
function withBoxUnlocked(body) {
let locked = box.locked;
if (!locked) {
return body();
}
box.unlock();
try {
return body();
} finally {
box.lock();
}
}
withBoxUnlocked(function() {
box.content.push("gold piece");
});
try {
withBoxUnlocked(function() {
throw new Error("Pirates on the horizon! Abort!");
});
} catch (e) {
console.log("Error raised:", e);
}
console.log(box.locked);
// → true
Error raised: Error: Pirates on the horizon! Abort!
true