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

伊谢尔伦
Release: 2017-07-18 11:21:04
Original
1207 people have browsed it

Whether the specified function exists

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

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;
  };
}
Copy after login

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"); 
}
Copy after login

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;
}
Copy after login

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template