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

secrets of the javascript Ninja(Function Type)(javascript忍者的秘密)

2009-03-30 22:25 363 查看
大多数情况下,typeof就可以完成检查函数类型的工作,例如:

function ninja(){}
alert(typeof ninja);


但是根据浏览器的不同,我们可以发现以下集中情况

在firefox2和firefox3中,如果检测一个<object/>类型的元素,将会检测出来是一个function

<!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=gb2312" />
<title>无标题文档</title>
<mce:script type="text/javascript"><!--
window.onload=function(){
var o=document.getElementById("doc_html");
alert(typeof o);
}
// --></mce:script>
</head>
<body>
<object id="doc_html" name="doc_html" style="LEFT: 0px; TOP: 0px" data=" gledit.htm" width=530 height=320 type=text/x-scriptlet VIEWASTEXT></object>
</body>
</html>


firefox2正则表达式会被认为是一个function;但是在firefox3中会被认为是object

IE6和IE7中一些dom元素的方法会被认为一个object

//typeof /test/=='function'
safari3中认为NodeList为function如:typeof document.body.childNodes =="function"

纵观以上所有情况,我们可以写出一个通用的函数来检测某个值是否是函数

function isFunction( fn ) {
return !!fn && !fn.nodeName && fn.constructor != String &&
fn.constructor != RegExp && fn.constructor != Array &&
/function/i.test( fn + "" );
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐