javascript_利用eval反射验证方法是否存在

来源:互联网 发布:java小数点后保留两位 编辑:程序博客网 时间:2024/05/22 09:47

<html>
<head>
<style type="text/css">
div
{
border:thin solid green;
width:200px;
height:100px;
}
</style>
<script type="text/javascript">
function hideOverflow()
{
document.getElementById("div1").style.overflow="hidden";
}
</script>
</head>
<body>
<script>
try{
alert(typeof(eval("hideOverflow")));
} catch(e) {
if(e.name!="ReferenceError")alert(e);
}
alert(1);
</script>
<div id="div1">
This is some text. This is some text. This is some text.This is some text. This is some text. This is some text.This is some text. This is some text. This is some text.
</div>
<br />
</body>
</html>

注意:eval("hideOverflow")会执行hideOverflow方法如果hideOverflow不存在该方法就回直接出错,

   所以使用try..catch来捕获异常,这是一个ReferenceError,

   typeof(eval("hideOverflow"))择会是一个function,可以利用这个来判断:

if(typeof(eval("hideOverflow"))=="function")alert("这是一个fun");