So i am lazy and like to give console.info a new function name 🙂 But i also like to be safe and make sure that i can leave my logging in and not error in browsers that don’t support console.
So i wrote this:
if (typeof console == "object" && typeof console.error == "function") {
e = console.info;
}
Now the problem only occurs in chrome and get the following error:
Uncaught TypeError: Illegal invocation
To me this seems like a very general error.
The most likely explanation is that the
consoleobject’sinfofunction expects thatthiswithin the function will be theconsoleobject. That won’t be the case if you do this:Remember that in JavaScript,
thisis defined entirely by how a function is called, not where it’s defined. More: Mythical methods and You must rememberthis.You’d have to do this instead:
…which obviously isn’t shorter.
So to do this reliably, you have to create a function instead:
jAndy pointed out we can also use
Function#bind(part of ES5) for this, since Chrome has that and, on Chrome,console.infois a real JavaScript function. So:That will only work on browsers that support ES5 (so, not IE8 and earlier for instance) and where
console.infois a real JavaScript function (some host-provided functions on some browsers are not, although I thinkconsole.infois on most if not all). But if you’re targeting Chrome, you’re golden. Also,bindis one of the ES5 features that’s trivial to implement in a non-ES5 browser (the es5-shim.js project and several others do). But implementingbindpurely for this one use is probably overkill, just use thefunction e(msg) { .. }above. 🙂Live example of all of the above