Home  >  Article  >  Web Front-end  >  How to determine whether functions and variables exist in JavaScript

How to determine whether functions and variables exist in JavaScript

coldplay.xixi
coldplay.xixiOriginal
2021-04-02 11:08:116859browse

Methods to determine whether functions and variables exist in JavaScript: 1. To determine whether the specified function exists, the code is [if (typeof(eval(funcName)) == "function")]; 2. To determine whether it exists Specify variables.

How to determine whether functions and variables exist in JavaScript

The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.

Methods to determine whether functions and variables exist in JavaScript:

1. Whether the specified function exists

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

2. Similar to the commonly used judgment functions in PHP Whether it 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;
 };
}

3. Determine whether the js function exists, if it exists, execute it

Assuming that funcName is the function name, use the following method to achieve the goal

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

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

Under normal circumstances, we use

if("undefined" != typeof downlm){ 
if(downlm=="soft"){ 
document.write('成功'); 
} 
}

to determine whether a variable exists alone. Related free learning recommendations: javascript(Video)

The above is the detailed content of How to determine whether functions and variables exist 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