Home >Web Front-end >JS Tutorial >Determine whether functions and variables exist in JavaScript_javascript skills

Determine whether functions and variables exist in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:56:181770browse

1. Whether the specified function exists

Copy code The code is as follows:

function isExitsFunction(funcName) {
Try {
If (typeof(eval(funcName)) == "function") {
             return true;
}
} catch(e) {}
Return false;
}

2. Similar to PHP’s commonly used judgment function, if it does not exist, create it

Copy code The code is as follows:

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, you can achieve the goal by using the following method

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

Copy code The code is as follows:

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

4. Whether the specified variable exists
Copy code The code is as follows:

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