JavaScript中判断函数、变量是否存在
本文主要介绍了JavaScript中判断函数、变量是否存在,用于保证js兼容性的情形
是否存在指定函数 function
function isExitsFunction(funcName) {
if (typeof(funcName) === "function") {
return true;
}
return false;
}
类似PHP常用的判断函数是否存在,不存在则创建
if (typeof String.prototype.endsWith != 'function') {
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
}
判断js函数是否存在,如果存在则执行
try
{
if(typeof(funcName)==="function")
{
funcName();
}
}catch(e)
{
//alert("not function");
}
是否存在指定变量
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;
}