Home  >  Article  >  Web Front-end  >  Two ways to determine whether a function in JavaScript has instance code

Two ways to determine whether a function in JavaScript has instance code

伊谢尔伦
伊谢尔伦Original
2017-07-18 11:25:541208browse

JS simple method to determine whether a function exists, involving operating skills related to javascript function running and type determination

First code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript" language="javascript" >
function showFace(unipcn,value){}
var isFunction =false;
try{
  //这里的代码需要用try一下,因为当showFace为定义时会抛出异常
  isFunction = typeof(eval(&#39;showFace&#39;))=="function";
}catch(e){}
if(isFunction) {
  alert(&#39;showFace is a Function!&#39;);
}else{
  alert(&#39;showFace is not a Function!&#39;);
}
</script>
</head>
<body>
</body>
</html>

Second code:

window.onload=function(){ 
try{ 
if(test&&typeof(test)=="function"){ 
test(); 
}else{ 
alert("不存在的函数"); 
} 
}catch(e){ 
} 
} 
function test(){ 
alert("函数执行……"); 
}

If it does not exist, an exception will be thrown, so try...catch must be added.

The above is the detailed content of Two ways to determine whether a function in JavaScript has instance code. 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