我一直在寻找一个解决方案,这一点我自己(我这是怎么找到你的问题)。
正如Tim指出的那样,在这种情况下,webkit浏览器(Safari,Chrome)依靠this
为console
。然而,Firefox并没有。因此,在FF中,您可以重新分配函数并保留行号(否则所有日志看起来像它们源自日志记录功能,这不是很有用)。检查您的浏览器的最佳方法是执行此操作并检查结果。以下是如何检查(在CoffeeScript中):
# Check to see if reassigning of functions work
f = console.log
assignSupported = true
try
f('Initializing logging...')
catch e
assignSupported = false
后来,当你的功能检查assignSupported并采取相应的行动:
levels =
ERROR: 1
WARN: 2
LOG: 3
INFO: 4
DEBUG: 6
log.setLevel = (newLevel) ->
for label, level of levels
if level > newLevel # Skip low levels
continue
name = label.toLowerCase()
f = -> # Fallback - empty function. In Js: var f = function() {}
if console?[name]
if assignSupported
f = console[name] # Wee, we'll have line numbers.
else
# Webkit need the this of console.log (namely, console)
# preserved, so we use a wrapper.
#
# Calling console[name] within the returned wrapper
# makes [name] a subject of the closure, meaning
# that it's the last value in the iteration -
# we need to preserve it.
f = ((n) ->
return (-> console[n].apply(console, arguments)))(name)
log[name] = f
log.setLevel levels.DEBUG
的线条:
f = ((n) ->
return (-> console[n].apply(console, arguments)))(name)
看起来有点奇怪。这是因为name
是循环变量,并且是词法绑定的,这意味着将使用执行时的值,它始终是最后的level
。它编译成这个JavaScript(如果它更易于阅读):
f = (function(n) {
return (function() {
return console[n].apply(console, arguments);
});
})(name);
它的WebKit的功能,而不是一个错误;-) https://bugs.webkit.org/show_bug.cgi?id=20141 – 2010-10-14 18:12:43
相关:http://stackoverflow.com/questions/14146316/why-does-scope-reduction-in-safari-break-existing-code – MvG 2013-04-19 13:57:34