重新认识 try catch 中的 finally
文章目录
今天在做一个拷贝函数, 要在 document.execCommand('copy') 的地方加异常处理。平时的习惯下面这样写,在得到结果后先移除 input 然后 return
function copyText(text) {
const inputElement = document.createElement('textarea');
Object.assign(inputElement.style, {
opacity: 0,
position: 'fixed',
top: 0
});
document.body.appendChild(inputElement);
inputElement.readOnly = true;
inputElement.value = text;
inputElement.select();
inputElement.setSelectionRange(0, text.length);
let result=false;
try {
result = document.execCommand('copy')
} catch (err) {}
document.body.removeChild(inputElement)
return result
}突发奇想,试下 finally 中来移除 input 。各位但是 finally 这个在 return 之后会不会执行啊。试了下居然会,并且 finally 中的代码先于 return 本身执行,返回值也正确。
try {
return document.execCommand('copy')
} catch (err) {
return false
} finally {
document.body.removeChild(inputElement)
}执行顺序验证代码
function test() {
try {
return console.log(1), 3;
} finally {
console.log(2)
}
}
console.log(test())输出:1,2,3
return 右边先执行,然后 finally, 最后 return 。感觉像找到一种在 return 后面还能执行代码的方式
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论