JavaScript中判断函数、变量是否存在
一、是否存在指定函数
functionisExitsFunction(funcName){
try{
if(typeof(eval(funcName))=="function"){
returntrue;
}
}catch(e){}
returnfalse;
}
二、类似PHP常用的判断函数是否存在,不存在则创建
if(typeofString.prototype.endsWith!='function'){
String.prototype.endsWith=function(suffix){
returnthis.indexOf(suffix,this.length-suffix.length)!==-1;
};
}
三、判断js函数是否存在,如果存在则执行
假设funcName为函数名字,用如下方法就可以达到目标
一定要添加trycatch块,否则不起作用。
try
{
if(typeof(eval(funcName))=="function")
{
funcName();
}
}catch(e)
{
//alert("notfunction");
}
四、是否存在指定变量
functionisExitsVariable(variableName){
try{
if(typeof(variableName)=="undefined"){
//alert("valueisundefined");
returnfalse;
}else{
//alert("valueistrue");
returntrue;
}
}catch(e){}
returnfalse;
}
一般情况下,我们单独判断变量是否存在都是用
if("undefined"!=typeofdownlm){
if(downlm=="soft"){
document.write('成功');
}
}
这样就不会因为直接使用变量导致出错了,适用于页面改版,旧页面没有变量赋值的情况。
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短