JavaScript中判断函数、变量是否存在

时间:2015-06-10    点击:54   

一、是否存在指定函数

复制代码 代码如下:

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;
}

JavaScript中String.match()方法的使用详解
JavaScript中操作字符串之localeCompare()方法的使用
JavaScript中的getMilliseconds()方法使用详解
在JavaScript中处理时间之getHours()方法的使用
详解JavaScript中getFullYear()方法的使用
> 返回     
地址:上海市普陀区胶州路941号长久商务中心 电话: QQ:
© Copyright 2012 上海网络 Product All Rights Reserved