您好,欢迎访问一九零五行业门户网

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; }
混合代码:
//是否存在指定函数 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中如何判断函数和变量存在的实例代码详解的详细内容。
其它类似信息

推荐信息