我不明白为什么它总是输出一个错误,而catch块却从不执行。
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(funct){
try{
console.log(funct);// thinks that everything is fine although there is a mistake
box.lock();
}
catch(e){//why doesn't it execute catch block ?
console.log("used catch");
box.unlock();
withBoxUnlocked(funct);
}
}
withBoxUnlocked(box.content);
发布于 2020-04-12 19:48:45
在代码中的这一点:
withBoxUnlocked(box.content);
运行时必须调用getter函数。这发生在函数被调用之前的。因此,函数中的try/catch
永远不会到达。
您可以通过更改withBoxUnlocked()
函数的工作方式来进行更改,以演示所发生的事情:
function withBoxUnlocked(object, property){
try{
console.log(object[property]);// thinks that everything is fine although there is a mistake
box.lock();
}
catch(e){//why doesn't it execute catch block ?
console.log("used catch");
box.unlock();
withBoxUnlocked(object, property);
}
}
withBoxUnlocked(box, "content");
这样,在到达try
子句之前,不会尝试访问该属性。
https://stackoverflow.com/questions/61170910
复制相似问题