欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

JavaScript中如何判断函数和变量存在的实例代码详解

程序员文章站 2022-05-12 07:49:51
...
是否存在指定函数
function isExitsFunction(funcName) {
    try {
        if (typeof(eval(funcName)) == "function") {
            return true;
        }
    } catch(e) {}
    return false;
}

类似PHP常用的判断函数是否存在,不存在则创建

if (typeof String.prototype.endsWith != 'function') {
  String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
  };
}

判断js函数是否存在,如果存在则执行

假设funcName为函数名字,用如下方法就可以达到目标

一定要添加try catch块,否则不起作用。

try 
{  
  if(typeof(eval(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;
}

混合代码:

//是否存在指定函数 
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;
}

以上就是JavaScript中如何判断函数和变量存在的实例代码详解的详细内容,更多请关注其它相关文章!