js判断是否存在指定变量或函数

//是否存在指定变量
function isExitsVariable(variableName) {
try {
if (typeof(eval(variableName)) == "undefined") {
console.log("已声明变量,但未初始化");
return false;
} else {
console.log("已声明变量,且已经初始化");
return true;
}
} catch(e) {
console.log("未声明变量");
}
return false;
}


//是否存在指定函数 
function isExitsFunction(funcName) {
    try {
        if (typeof(eval(funcName)) == "function") {
            return true;
        }
    } catch(e) {}
    return false;
}

 调用方法:

alert(isExitsVariable('xx'));

var xx;

alert(isExitsVariable('xx'));

var xx = 123;

alert(isExitsVariable('xx'));