Home >Web Front-end >JS Tutorial >Detailed explanation of example code on how to determine the existence of functions and variables in JavaScript

Detailed explanation of example code on how to determine the existence of functions and variables in JavaScript

伊谢尔伦
伊谢尔伦Original
2017-07-18 11:21:041205browse

Whether the specified function exists

function isExitsFunction(funcName) {
    try {
        if (typeof(eval(funcName)) == "function") {
            return true;
        }
    } catch(e) {}
    return false;
}

Similar to the commonly used PHP judgment function exists, create it if it does not exist

if (typeof String.prototype.endsWith != 'function') {
  String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
  };
}

Judge whether the js function exists, if it exists, execute it

Assuming that funcName is the function name, the goal can be achieved by using the following method

Be sure to add a try catch block, otherwise it will not work.

try 
{  
  if(typeof(eval(funcName))=="function")  
  {
      funcName();
  }
}catch(e)
{
//alert("not function"); 
}

Whether the specified variable exists

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

Mixed code:

//是否存在指定函数 
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;
}

The above is the detailed content of Detailed explanation of example code on how to determine the existence of functions and variables in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn