您的位置:首页 > Web前端 > JavaScript

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

2012-02-20 23:09 471 查看
<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");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息