Home > Web Front-end > JS Tutorial > body text

How to determine whether functions and variables exist in JavaScript

coldplay.xixi
Release: 2023-01-04 09:34:10
Original
6859 people have browsed it

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

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

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

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

Under normal circumstances, we use

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!