window.console.log
在Internet Explorer 9中的哪些情况下被定义?
即使window.console.log
被定义,window.console.log.apply
和window.console.log.call
仍未定义。为什么会这样?
[IE8相关问题:IE8中的console.log发生了什么?.]
window.console.log
在Internet Explorer 9中的哪些情况下被定义?
即使window.console.log
被定义,window.console.log.apply
和window.console.log.call
仍未定义。为什么会这样?
[IE8相关问题:IE8中的console.log发生了什么?.]
console
对象。如果隐藏该选项卡的开发人员工具窗口,则console
对象将保持暴露状态,以便您导航到的每个页面都可以使用。如果打开一个新选项卡,则必须为该选项卡打开开发人员工具,以便公开console
对象。
console
对象不是任何标准的一部分,它是文档对象模型的扩展。像其他DOM对象一样,它被认为是主机对象,并且不需要从Object
继承,也不需要像本机ECMAScript函数和对象那样从Function
继承其方法。这就是为什么这些方法上的apply
和call
未定义的原因。在IE 9中,大多数DOM对象都得到了改进,以从本机ECMAScript类型继承。由于开发人员工具被认为是IE的扩展(尽管是内置扩展),因此它们显然没有像DOM的其余部分那样获得相同的改进。
值得注意的是,您仍然可以在一些console
方法上使用一些Function.prototype
方法,只需使用一些bind()
技巧即可。var log = Function.prototype.bind.call(console.log, console);
log.apply(console, ["this", "is", "a", "test"]);
//-> "thisisatest"
console
对象也是这样。 - Marcel Korpelif (!window.console) window.console = {};
if (!window.console.log) window.console.log = function () { };
这对我在所有浏览器中都有效。它创建了一个虚拟函数来模拟 console.log 当调试器不活动时。当调试器处于活动状态时,方法console.log被定义并正常执行。
我知道这是一个非常老的问题,但感觉这增加了一个有价值的解决控制台问题的可选方法。将以下代码放在对console.*的任何调用之前(因此是你的第一个脚本)。
// Avoid `console` errors in browsers that lack a console.
(function() {
var method;
var noop = function () {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
参考:
https://github.com/h5bp/html5-boilerplate/blob/v5.0.0/dist/js/plugins.js
只有在控制台打开时才会定义console.log。如果你想在你的代码中检查它,请确保在window属性内检查它
if (window.console)
console.log(msg)
在IE9中,这会抛出异常并且不会正确工作。不要这样做。
if (console)
console.log(msg)
在阅读Marc Cliament上面评论的文章后,我现在已经将我的全能跨浏览器console.log函数更改为以下形式:
function log()
{
"use strict";
if (typeof(console) !== "undefined" && console.log !== undefined)
{
try
{
console.log.apply(console, arguments);
}
catch (e)
{
var log = Function.prototype.bind.call(console.log, console);
log.apply(console, arguments);
}
}
}
Function.prototype.apply.call(console.log, console, arguments);
。 - Victor怎么样...
console = { log : function(text) { alert(text); } }