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

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

伊谢尔伦
Release: 2017-07-18 11:25:54
Original
1291 people have browsed it

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

Second code:

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

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!

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