在IE7中,什么会导致这种行为?我无法在 jsfiddle 上重现此问题...
var func=new Function('arg','return 2*2;');
alert(typeof func);
返回对象。
我完全糊涂了。
如何调试此问题?如何弄清楚为什么新函数返回一个对象?
更新
不应该是这样吧?还是我只是不明白什么?对我来说,它看起来像Windows 8的错误。
https://www.dropbox.com/s/mhyuab3mhj2yu59/ie7_windows8_bug.png
更新
这是IE8,在IE9中它消失了。
我无法在我的机器上复制这个,而你的权利 - 这是错误的。 任何callable
的东西都应根据 EMCA 规范为typeof
操作员返回function
。 如果你想在面对这个问题时测试给定变量是否是一个函数,你可以使用:
function isFunction(func){
return typeof func === 'function' ||
(typeof func === 'object' && func instanceof Function);
}
扩展马克·罗德斯的答案
function realType( t ) {
return Object.prototype.toString.call(t).slice(8, -1);
};
var func=new Function('arg','return 2*2;');
alert( realType(func) ); // Function/Object
alert( realType([]) ); // Array
alert( typeof [] ) // object
alert( realType(new Date) ); // Date
alert( typeof (new Date) ); // object
通过此解决方案解决了问题:
var func=eval('(function(){return function(){ your code here }})()');