JavaScript中判断函数、变量是否存在
作者:bea
一、是否存在指定函数 function isExitsFunction(funcName) { try { if (typeof(eval(funcName)) == "function") { return true; } } catch(e) {} return false;} 二、类似PHP常用的判断函数是否存在,不存在则创建 if (typeof String.prototype.endsWith != 'function'
一、是否存在指定函数
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('成功');
}
}
这样就不会因为直接使用变量导致出错了,适用于页面改版,旧页面没有变量赋值的情况。
有用 | 无用
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('成功');
}
}
这样就不会因为直接使用变量导致出错了,适用于页面改版,旧页面没有变量赋值的情况。
有用 | 无用
猜你喜欢
您可能感兴趣的文章:
- Javascript中的getUTCHours()方法使用详解
- jQuery实现首页图片淡入淡出效果的方法
- 简介JavaScript中的getUTCFullYear()方法的使用
- javascript中一些util方法汇总
- Javascript中的getUTCDay()方法使用详解
- 在JavaScript中操作时间之getUTCDate()方法的使用
- JavaScript中的getTimezoneOffset()方法使用详解
- ajax读取数据后使用jqchart显示图表的方法
- jquery获取当前元素索引值用法实例
- jQuery实现checkbox全选的方法
- JavaScript中的getTime()方法使用详解
- 简介JavaScript中的getSeconds()方法的使用
- 在JavaScript中操作时间之getMonth()方法的使用
- 在JavaScript中用getMinutes()方法返回指定的分时刻
- JavaScript中的getMilliseconds()方法使用详解
- 在JavaScript中处理时间之getHours()方法的使用
- JavaScript中计算网页中某个元素的位置
- JavaScript实现强制重定向至HTTPS页面
- 详解JavaScript中getFullYear()方法的使用