Home > Article > Web Front-end > Detailed explanation of example code on how to determine the existence of functions and variables in JavaScript
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!