当前位置: 首页 > Web前端 > JavaScript

终于在trycatch中重新认识了

时间:2023-03-27 10:02:52 JavaScript

今天做一个copy函数,需要在document.execCommand('copy')的地方加上异常处理。通常的习惯如下。得到结果后,去掉输入,然后返回functioncopyText(text){constinputElement=document.createElement('textarea');Object.assign(inputElement.style,{opacity:0,position:'fixed',top:0});document.body.appendChild(inputElement);inputElement.readOnly=true;inputElement.value=文本;inputElement.select();inputElement.setSelectionRange(0,text.length);让结果=假;try{result=document.execCommand('copy')}catch(err){}document.body.removeChild(inputElement)returnresult}一时兴起,试着把finally中的input去掉。大家好,不过最后这个会在return之后执行。试了一下,成功了,在return本身之前执行了finally中的代码,返回值是正确的。try{returndocument.execCommand('copy')}catch(err){returnfalse}finally{document.body.removeChild(inputElement)}执行顺序验证代码functiontest(){try{returnconsole.log(1),3;}finally{console.log(2)}}console.log(test())output:1,2,3return右边先执行,然后finally,最后return。感觉就是找到return后执行代码的方法