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

网络编程 发布日期:2024/10/6 浏览次数:1

正在浏览:JavaScript中判断函数、变量是否存在

一、是否存在指定函数

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

一般情况下,我们单独判断变量是否存在都是用

if("undefined" != typeof downlm){ 
if(downlm=="soft"){ 
document.write('成功'); 
} 
}

这样就不会因为直接使用变量导致出错了,适用于页面改版,旧页面没有变量赋值的情况。

Windows上运行安卓你用过了吗
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。