我遇到了同样的IE问题,并为此编写了一种例程。
它不像上面所有实现那样花哨,但它在所有现代浏览器中都能工作。
我使用Firefox(Firebug),IE 7,8,9 Chrome和Opera进行了测试。
它利用了邪恶的EVAL,但您只想在开发中进行调试。
之后,您将使用
debug = function() {};
替换代码。
所以这就是它。
问候,汉斯
(function(ns) {
var msgs = [];
function argtoarr (args,from) {
var a = [];
for (var i = from || 0; i<args.length; i++) a.push(args[i]);
return a;
}
function log(arg) {
var params = "", format = "", type , output,
types = {
"number" : "%d",
"object" : "{%o}",
"array" : "[%o]"
};
for (var i=0; i<arg.length; i++) {
params += (params ? "," : "")+"arg["+i+"]";
type = types[toType(arg[i])] || "%s";
if (type === "%d" && parseFloat(arg[i]) == parseInt(arg[i], 10)) type = "%f";
format += (format ? "," : "")+type;
}
output = "console.log("+(window.opera ? "" : "'%f',".replace("%f",format))+"%p);".replace("%p",params);
eval(output);
}
ns.debug = function () {
msgs.push(argtoarr(arguments));
if (console !== undefined) while (msgs.length>0) log(msgs.shift());
}
})(window);
糟糕,我忘记了我的toType函数,这是它。
function toType(obj) {
if (obj === undefined) return "undefined";
if (obj === null) return "null";
var m = obj.constructor;
if (!m) return "window";
m = m.toString().match(/(?:function|\[object)\s*([a-z|A-Z|0-9|_|@]*)/);
return m[1].toLowerCase();
}
Function#bind
。如果你使用的实现还没有完全符合 ECMAScript5 规范,就必须提供这个依赖。 - T.J. Crowderfunction debug() { Function.prototype.apply.call(console.log, console, arguments); }
,这本质上就是这个bind
-ing 代码所做的。 - Sophie Alpert