本文介绍了在JavaScript中判断指定函数或变量是否存在的两种实用方法。通过封装isExitsFunction和isExitsVariable函数,利用try-catch块捕获异常并结合typeof运算符,可安全检测全局作用域下的函数与变量状态,避免引用未定义对象导致的运行错误。
JavaScript判断函数与变量是否存在的实现方法
核心代码
//是否存在指定函数
function isExitsFunction(funcName) {
try {
if (typeof(eval(funcName)) == "function") {
return true;
}
} catch(e) {}
return false;
}
//是否存在指定变量
function isExitsVariable(variableName) {
try {
if (typeof(variableName) == "undefined") {
//alert("value is undefined");
return false;
} else {
//alert("value is true");
return true;
}
} catch(e) {}
return false;
}
如需了解更多的判断技巧,可参考这篇文章:https://www.jb51.net/article/67551.htm