Like all programmers, I’m lazy. So in my utils.js there’s a simple line:
window.log = console.log
This works fine in firefox, but it makes Chrome cry like a little boy. I have to write console.log to make it work.
Any suggestions?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Chrome’s
console.logapparently pays attention to whatthisis so if you do this:Then you’ll get nothing more than a “TypeError: Illegal invocation” exception for your efforts. However, if you force the appropriate context thusly:
then you’ll get your
pancakesin the console. That’s why you need to wrapconsole.login a function if you want to be lazy and just saylog: someconsole.logimplementations need to be called with the appropriate context.However, just
window.log = (x) -> console.log(x)is not quite correct asconsole.logis a variadic function. A better implementation would be this:or to be pedantic, since
argumentsisn’t an array andFunction#applyexpects an array, “cast”argumentsto a real array in the usual way:That should work the same everywhere and preserve the variadic nature of
console.log. I doubt you need to be that pedantic though, just sendingargumentsin and pretending it is an array should be fine. You could also use CoffeeScript splats as a short form of the[].sliceandargumentsstuff:If you look at the JavaScript version of that you’ll see that it is the
sliceandargumentsstuff in disguise.Of course if you’re using plain JavaScript, then one of these will work:
Another option is to use
Function#bindto forcelogto be called in the context ofconsole:The downside is that not every browser supports
bind.