Home >Web Front-end >JS Tutorial >Two ways to determine whether a function in JavaScript has instance code
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('showFace'))=="function"; }catch(e){} if(isFunction) { alert('showFace is a Function!'); }else{ alert('showFace is not a Function!'); } </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!