除了使用typeof还可以是用原型实例的方式去判断.
例如判断是否是Function 可以使用 a instanceof Function
这个instanceof操作符返回的是true/false 但效率比typeof低了25%左右.
当然是用instanceof不单可以判断是否是Function String Number Boolean Object Array等
还能用于判断是否是自定义的类原型例如:
function helloworld()
{
this.a = 0;
this.b = 1;
this.c = 2;
}
helloworld.prototype = {...}
var test = new helloworld();
alert(test instanceof helloworld);
var cc = new helloworld;
var test1 = new cc();
alert(test1 instanceof helloworld);.........这么宝贵的经验才10分
例如判断是否是Function 可以使用 a instanceof Function
这个instanceof操作符返回的是true/false 但效率比typeof低了25%左右.
当然是用instanceof不单可以判断是否是Function String Number Boolean Object Array等
还能用于判断是否是自定义的类原型例如:
function helloworld()
{
this.a = 0;
this.b = 1;
this.c = 2;
}
helloworld.prototype = {...}
var test = new helloworld();
alert(test instanceof helloworld);
var cc = new helloworld;
var test1 = new cc();
alert(test1 instanceof helloworld);.........这么宝贵的经验才10分
function ff(){
var ss
alert( typeof(ff) )//因为有ff这个函数所以正常
alert( typeof(ss) )//因为有ss这个变量所以正常
alert( typeof(bb) )//bb完全未定义,但用typeof也不会报错
</script>现在就是研究能不能写出一个函数,能完全代替if( typeof(xxxxx)=="xxxxx" )这么长的写法,
例如用isNull(bb)去判断这个完全未定义的bb,也不会报错的方法,值得研究吧,分数不重要哈。
只有if((a)&&isFunction(a))
{
... ...
}
这样调用了
例如isFunction('a'),然后isFunction里利用eval来转换,再配合try{}catch(e){},使浏览器不报错。例子代码:
<script>
function isFunction(name){
try{ var f=eval(name); if(typeof(f)=="function"){ return true }else{ return false }; }
catch(e){ return null }
}
function aa(){}
var bb=nullisFunction('aa')
isFunction('bb')
isFunction('cc')
</script>然后可以根据这个原理,可以写出一个通用的执行函数的function,即使函数不存在也不会有错。