gpt4 book ai didi

javascript - javascript HTML W/R/T Later 函数中如何处理未定义的错误

转载 作者:行者123 更新时间:2023-12-03 11:07:10 26 4
gpt4 key购买 nike

我遇到了一个我以前没有考虑过的问题。如果我有一个在每个页面上运行的 main.js 脚本,但我的一个或多个页面不包含该脚本引用的元素(例如,联系表单不在某个页面上,其中脚本运行)JavaScript 出错后代码会发生什么情况。似乎错误之后的任何代码都不会运行,即使我认为 Javascript 会忽略这些错误。例如:如果我有以下代码

var el = document.querySelector('#el'); //Not a real element
el.addEventListener('click', function () {
console.log('Here');
}, false);

//The console errors "can not add eventListener of null"

alert('Test'); //This will never execute?

最后一行永远不会执行吗?

最佳答案

来自specification :

If an algorithm is defined to “throw an exception”, execution of the algorithm is terminated and no result is returned. The calling algorithms are also terminated, until an algorithm step is reached that explicitly deals with the exception, using terminology such as “If an exception was thrown…”. Once such an algorithm step has been encountered the exception is no longer considered to have occurred.

尽管这主要解决规范中定义的算法,但由于程序的执行也在规范中定义,因此它也适用于用户域代码的执行。

所以,是的,最后一行不会被执行,因为抛出错误时程序将终止。

关于javascript - javascript HTML W/R/T Later 函数中如何处理未定义的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27790515/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com