正常情况下,可以直接 Object.prototype.toString.apply(obj)=='[object Function]',就可以判断了,但是iE这个奇葩,它不能正确认识一些dom操作方法,例如document.getElementById,document.appendChild。还有alert,confirm这些方法,如果调用上面这行代码它会返回false。通过alert(typeof alert);//object 可以发现ie把alert当成了对象,事情总是有办法解决的,解决办法就是通过判断传入对象是否是以function开始定义的。应用正则表达式就可以了。(本例还使用了惰性载入函数,减少了每次调用都要去判断if条件的次数,提高了代码的执行效率)
var isFunction=(function(){
if("object"===typeof alert )//说明是ie{
alert(''+alert);//function alert(){[native code]}
return function(obj){
try{
alert(''+obj);
return /\s*\bfunction\b/.test(''+obj);
}catch(e){
return false;
}
};
}
else{
return function(obj){
return Object.prototype.toString.apply(obj)=='[object Function]';
};
}
})();
var func=function(){};
var regexp=/\s*/g;
alert(isFunction(func));
alert(isFunction(regexp));
alert(isFunction(alert));//在ie下面返回false,在ie中将dom操作方法getElementById等,
//以及alert。confirm方法都认为不是function,而是一个object
//解决方法是,判断一个对象
alert(isFunction(isFunction));/*
* function(obj){
try{
alert(''+obj);
return /\s*\bfunction\b/.test(''+obj);
}catch(e){
return false;
}
}
* */