我一直在尋找一個解決方案,這一點我自己(我這是怎麼找到你的問題)。
正如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