将console.log分配给另一个对象(Webkit问题) [英] Assigning console.log to another object (Webkit issue)

查看:164
本文介绍了将console.log分配给另一个对象(Webkit问题)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保持我的日志语句尽可能短,同时防止控制台在不存在时被访问;我想出了以下解决方案:

I wanted to keep my logging statements as short as possible while preventing console from being accessed when it doesn't exist; I came up with the following solution:

var _ = {};
if (console) {
    _.log = console.debug;
} else {
    _.log = function() { }
}


$ b b

对我来说,这看起来很优雅,它在Firefox 3.6中很好用(包括保留使 console.debug 比<$ c $更有用的行号c> console.log )。但它不工作在Safari 4. [更新:或在Chrome。所以问题似乎是Firebug和Webkit控制台之间的区别。]如果我按照上面的

To me, this seems quite elegant, and it works great in Firefox 3.6 (including preserving the line numbers that make console.debug more useful than console.log). But it doesn't work in Safari 4. [Update: Or in Chrome. So the issue seems to be a difference between Firebug and the Webkit console.] If I follow the above with

console.debug('A')
_.log('B');

第一个语句在两个浏览器中均可正常工作,但第二个语句会生成TypeError:Type Error苹果浏览器。这只是Firebug和Safari Web开发工具如何实现控制台之间的区别?如果是这样,它是非常恼人的苹果 Webkit的一部分。将控制台函数绑定到原型,然后实例化,而不是直接绑定到对象,这没有帮助。

the first statement works fine in both browsers, but the second generates a "TypeError: Type Error" in Safari. Is this just a difference between how Firebug and the Safari Web Developer Tools implement console? If so, it is VERY annoying on Apple's Webkit's part. Binding the console function to a prototype and then instantiating, rather than binding it directly to the object, doesn't help.

我可以,当然,只需调用 console.debug 从分配给 _。log 的匿名函数,但是我会丢失我的行号。任何其他想法?

I could, of course, just call console.debug from an anonymous function assigned to _.log, but then I'd lose my line numbers. Any other ideas?

推荐答案

首先,如果 console 确实未定义因为它是在浏览器,如IE),你会得到一个错误。您应该检查它作为全局对象的属性,它在浏览器中是 window 。一般来说,在使用之前测试一个特性也是个好主意,所以我为 debug 方法添加了一个测试。

First, if console is indeed undefined (as it is in browsers such as IE), you'll get an error. You should check it instead as a property of the global object, which is window in browsers. It's also a good idea in general to test a feature before using it, so I've added a test for the debug method.

Safari中的 console.debug 的实现可能取决于它的值 this console ,如果使用 _调用它就不会出现这种情况log 将引用 _ )。做了一个快速测试,似乎是这种情况,下面的问题解决了:

Possibly the implementation of console.debug in Safari relies on its value of this being a reference to console, which will not be the case if you call it using _.log (this will instead be a reference to _). Having done a quick test, this does seem to be the case and the following fixes the problem:

var _ = {};
if (typeof window.console != "undefined"
       && typeof window.console.debug == "function") {
    _.log = function() {
        window.console.debug.apply(window.console, arguments);
    }
} else {
    _.log = function() { }
}

这篇关于将console.log分配给另一个对象(Webkit问题)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆