是否可以在全局(窗口)范围内捕获未定义的引用是浏览器并且需要函数而不是抛出错误而不将所有函数包装在try-catch中?
实施例。我有功能
$('#id').on('click', function(){
a();
})
如果未定义a
函数,我只会收到错误Uncaught ReferenceError: a is not defined
我想要的是 - 定义一些全局函数来捕获所有这些错误,并且需要所需的文件(基于地图)而不是抛出错误。
我知道nodejs可以捕获任何错误,但是在浏览器中是否可以?
答案 0 :(得分:1)
你不能只检查类型吗?
if (typeof a !== 'undefined') {
//execute the function
a();
} else {
//do something else
console.log('not defined');
}
我认为if (typeof a == 'function') {...}'
会更加明确。
以下是关于typeof
的更多信息:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
答案 1 :(得分:0)
仅仅在调用之前检查是否存在是不够的?
.container {
height: 3000px;
}
#trigger {
position: relative;
top: 300px;
}
.katrori {
opacity: 0;
position:relative;
top:300px;
background-color:#eee;
height:400px;
padding:25px;
font-family:Arial, Sans-serif;
font-weight:bold;
}